I can provide an O(n) sorting algorithm, but with an important caveat: true O(n) comparison-based sorting is theoretically impossible for arbitrary data (the lower bound is O(n log n)). However, for floating-point numbers with known constraints, we can use counting sort or radix sort variants that achieve O(n) complexity.
Here's a radix sort implementation for positive floats:
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
void radix_sort_floats(float arr[], int n) {
if (n <= 1) return;
// Convert floats to unsigned integers for bit manipulation
uint32_t *temp = (uint32_t*)malloc(n * sizeof(uint32_t));
uint32_t *output = (uint32_t*)malloc(n * sizeof(uint32_t));
// Convert float to unsigned int representation
for (int i = 0; i < n; i++) {
uint32_t bits = *(uint32_t*)&arr[i];
// Handle sign bit: if negative, flip all bits; if positive, flip only sign bit
temp[i] = (bits & 0x80000000) ? ~bits : bits | 0x80000000;
}
// Radix sort on each byte (4 passes for 32-bit values)
for (int byte = 0; byte < 4; byte++) {
int count[256] = {0};
// Count occurrences of each byte value
for (int i = 0; i < n; i++) {
count[(temp[i] >> (byte * 8)) & 0xFF]++;
}
// Calculate cumulative counts
for (int i = 1; i < 256; i++) {
count[i] += count[i - 1];
}
// Build output array
for (int i = n - 1; i >= 0; i--) {
int idx = (temp[i] >> (byte * 8)) & 0xFF;
output[--count[idx]] = temp[i];
}
// Copy back to temp
memcpy(temp, output, n * sizeof(uint32_t));
}
// Convert back to floats
for (int i = 0; i < n; i++) {
uint32_t bits = temp[i];
// Reverse the sign bit transformation
bits = (bits & 0x80000000) ? bits & 0x7FFFFFFF : ~bits;
arr[i] = *(float*)&bits;
}
free(temp);
free(output);
}
int main() {
float arr[] = {3.14, -2.5, 0.0, 1.23, -5.67, 9.99, -0.5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < n; i++) {
printf("%.2f ", arr[i]);
}
printf("\n");
radix_sort_floats(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%.2f ", arr[i]);
}
printf("\n");
return 0;
}
This implementation uses radix sort on the binary representation of floats. The time complexity is O(n × k) where k is the number of bytes (4 for 32-bit floats), making it O(n) since k is constant.
The algorithm works by:
Converting floats to unsigned integers while preserving order
Performing radix sort on each byte (4 passes)
Converting back to floats
Note that this approach works for all IEEE 754 floats including negative numbers, zero, and special values. For specific constraints (like only positive integers stored as floats), simpler O(n) algorithms like counting sort could be used.