简体   繁体   中英

O(n) sorting algorithm

Here's a very horrible sorting algorithm that only works on integers ranging from 0 to size. I wouldn't use such an algorithm on a large set of data or one with large numbers in it because it would require so much memory. That consider, wouldn't this 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};

    for (int n=0; n<size; n++) b[n] = 0;

    for (int n=0; n<size; n++){
        if (size <= a[n]) throw std::logic_error("error");
        b[a[n]]++;
    }

    int x = 0;
    for (int n=0; n<size; n++){
        for (int t=0; t<b[n]; t++){
            a[x] = n;
            x++;
        }
    }

    for (int n=0; n<size; n++) printf("%d ",a[n]);
}

You're showing a variation on radix sort . Along with bucket sort , these algorithms are prime examples of sorting not based on comparison, which can offer better complexity than O(n logn) .

Do note, however, that your implementation is actually O(n + size) .

It is O(n) . More specifically it is O(n+k) where n is the number of elements in input array and k is the range of input in your case size. You are just keeping counts of all elements which occur in the array. And then you just store them in increasing order as many times as they occur in the original array. This algorithm is called count sort.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM