I red already that the best sort comparison algorithms have complexity O(nlog(n)). But I'm asked to sort an array of integers(in C) using a sorting algorithm of complexity O(n) given that all the elements in the array are non-negative and less than a constant K. But I have no idea how to use this information in the sorting algorithm. You guys have any idea?
4 Answers
That's a simple one (known as "counting sort" or "histogram sort", a degenerate case of "bucket sort"):
- Allocate an array with one slot for each non-negative integer less than
k, and zero it.O(k) - Iterate over all elements of the input and count them in our array.
O(n) - Iterate over our array and write the elements out in-order.
O(n+k)
Thus, O(n+k).
2 Comments
create a new array of size K and just insert each element to the array in it own position..
lets say K=100
create an array of 100 integers - clear it. and if you have the set {55, 2, 7, 34}. you just need to the following:
array[55] = 1;
array[2] = 1;
array[7] = 1;
array[34] =1;
And the go over the array from start to end and just print the index of the cells that are == 1
Comments
Depends on the kind of complexity. Average case O(n+k): Bucket Sort.
Radix sort should be O(m * n) though. (m being the length of the key used to sort)
1 Comment
O(n log K), not O(nK).
O(n log n).