Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array with elements ranging from 0 to 9999

Tags:

c++

algorithm

I recently stumbled upon a C++ problem. Here goes.

Suppose you know that all the values in an integer array fall into the range 0 to 9999. Show that it is possible to write a O(N) algorithm to sort arrays with this restriction

To my understanding an algorithm of O(N) is one where you go through a certain set of O(1) operations N times. Now for the life of me I can't comprehend how you would go about writing a program that sorts an array of numbers with respect to O(N). Sorting in its most basic form consists of comparing numbers with each other and there is no algorithm for doing that in one iteration and ending up with a sorted array.

In the question it makes the point that an element of this array can only have the value within the range of 0-9999. I can understand from the question that this restriction is what makes the whole thing possible and I should use it in my Algorithm in order to reach a solution. But I'm still getting nowhere. All the sorting Algorithms that I know of (Selection, Insertion, Merge, Quick ...) all have running times larger than O(N) with the minimum being O(log N).

I can understand that some of these algorithms can have running times of O(N), but only on their best cases. But I don't think the question is being asked in that respect.

If anyone can shed any insight on this problem I would appreciate it.

like image 242
Micky Avatar asked Apr 26 '11 11:04

Micky


People also ask

Which algorithm is best for sorting 100000 elements?

You can avoid a full sort by using a variation of heapsort. Normally in a heapsort you build a heap of the entire data set (100,000 elements in your case). Instead, only allow the heap to grow to 20,000 elements. Keep the largest element at the top of the heap.

Which of the following is best running time to sort n integers in the range 0 to n2 1?

n numbers in range from 0 to n2 – 1? The idea is to use Radix Sort.


2 Answers

Radix sort. O(4n) is O(n).

like image 122
Pontus Gagge Avatar answered Nov 15 '22 06:11

Pontus Gagge


Counting sort (see http://en.wikipedia.org/wiki/Counting_sort). Only comparison sorts are Omega(n lg n).

like image 44
Stuart Golodetz Avatar answered Nov 15 '22 07:11

Stuart Golodetz