c++ - O(n) sorting algorithm -
here's horrible sorting algorithm works on integers ranging 0 size. wouldn't use such algorithm on large set of data or 1 large numbers in because require memory. consider, wouldn't algorithm technically run in o(n) time?
thanks
#include <iostream> #define size 33 int main(){ int b[size]; int a[size] = {1,6,32,9,3,7,4,22,5,2,1,0}; (int n=0; n<size; n++) b[n] = 0; (int n=0; n<size; n++){ if (size <= a[n]) throw std::logic_error("error"); b[a[n]]++; } int x = 0; (int n=0; n<size; n++){ (int t=0; t<b[n]; t++){ a[x] = n; x++; } } (int n=0; n<size; n++) printf("%d ",a[n]); }
you're showing variation on radix sort. along bucket sort, these algorithms prime examples of sorting not based on comparison, can offer better complexity o(n logn)
.
do note, however, implementation o(n + size)
.
Comments
Post a Comment