1

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]);
}
4
  • 1
    You could verify that experimentally... :P Commented Sep 22, 2016 at 15:32
  • 1
    Look at Counting_sort. Commented Sep 22, 2016 at 15:33
  • Pretty much yes. Read here: en.wikipedia.org/wiki/Bucket_sort Commented Sep 22, 2016 at 15:37
  • Why is it horrible? For the right sort of problem, it can be very efficient. Commented Sep 22, 2016 at 16:32

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.