Certainly! To sort a list of floats in O(n) time, you need to use a non-comparison-based sorting algorithm. The most common O(n) sorting algorithms are Counting Sort, Radix Sort, and Bucket Sort. However, Counting Sort and Radix Sort are typically used for integers. For floats, Bucket Sort is a good choice, especially if the floats are uniformly distributed over a known range (e.g., [0, 1)).
Below is an O(n) implementation of Bucket Sort in C for sorting an array of floats in the range [0, 1):
#include <stdio.h>
#include <stdlib.h>
#define N 10 // Number of elements
// Node structure for linked list (for buckets)
typedef struct Node {
float value;
struct Node* next;
} Node;
// Function to insert a value into a sorted linked list
void insert_sorted(Node** head, float value) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->value = value;
new_node->next = NULL;
if (*head == NULL || (*head)->value >= value) {
new_node->next = *head;
*head = new_node;
} else {
Node* current = *head;
while (current->next != NULL && current->next->value < value) {
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
}
// Function to free the linked list
void free_list(Node* head) {
while (head) {
Node* temp = head;
head = head->next;
free(temp);
}
}
// Bucket Sort function
void bucket_sort(float arr[], int n) {
// Create n empty buckets
Node* buckets[N] = {NULL};
// Put array elements in different buckets
for (int i = 0; i < n; i++) {
int idx = (int)(arr[i] * n); // Index in bucket
if (idx >= n) idx = n - 1; // Handle edge case for arr[i] == 1.0
insert_sorted(&buckets[idx], arr[i]);
}
// Concatenate all buckets into arr[]
int index = 0;
for (int i = 0; i < n; i++) {
Node* node = buckets[i];
while (node) {
arr[index++] = node->value;
node = node->next;
}
free_list(buckets[i]);
}
}
// Test the bucket sort
int main() {
float arr[N] = {0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68};
printf("Original array:\n");
for (int i = 0; i < N; i++)
printf("%f ", arr[i]);
printf("\n");
bucket_sort(arr, N);
printf("Sorted array:\n");
for (int i = 0; i < N; i++)
printf("%f ", arr[i]);
printf("\n");
return 0;
}
Notes:
- This implementation assumes all floats are in the range [0, 1). If your floats are in a different range, you need to normalize them.
- The average time complexity is O(n) if the input is uniformly distributed.
- For general float values (not in [0, 1)), you can modify the bucket index calculation accordingly.
If you need a version for floats in an arbitrary range, let me know!