Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort array of size n

Tags:

c++

arrays

c

if an array of size n has only 3 values 0 ,1 and 2 (repeated any number of times) what is the best way to sort them. best indicates complexity. consider space and time complexity both

like image 331
Gaurav Kushwaha Avatar asked Apr 12 '10 12:04

Gaurav Kushwaha


People also ask

How do you sort an array by size?

To sort strings in an array based on length in JavaScript, call sort() method on this string array and pass a comparison function to sort() method, such that the comparison happens for the length of elements.

How do you sort an array in log n complexity?

It essentially follows two steps: Divide the unsorted list into sub-lists until there are N sub-lists with one element in each ( N is the number of elements in the unsorted list). Merge the sub-lists two at a time to produce a sorted sub-list; repeat this until all the elements are included in a single list.

What is sort Arr Arr n?

For arrays, array name arr indicates iterator pointing to first element of array and +n would increment that iterator by n elements. In your case, the sort algorithm should take beginning iterator and iterator pointing to one beyond last element.


4 Answers

Count the occurences of each number and afterward fill the array with the correct counts, this is O(n)

like image 147
Andreas Brinck Avatar answered Sep 30 '22 20:09

Andreas Brinck


Sound's a lot like Dijkstra's Dutch National Flag Problem.

If you need a solution that doesn't use counting, check out http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Flag/

like image 27
Gabe Avatar answered Sep 30 '22 21:09

Gabe


Untested C-style solution:

int count[3] = {0, 0, 0};

for (int i = 0; i < n; ++i)
    ++count[array[i]];

int pos = 0;
for (int c = 0; c < 3; ++c)
    for (int i = array[c]; i; --i)
        array[pos++] = c;
like image 29
Fred Avatar answered Sep 30 '22 19:09

Fred


Haskell two-liner:

count xs = Map.toList $ Map.fromListWith (+) [ (x, 1) | x <- xs ]

countingSort xs = concatMap ( \(x, n) -> replicate n x) (count xs)

> countingSort [2,0,2,1,2,2,1,0,2,1]
[0,0,1,1,1,2,2,2,2,2]
like image 26
fredoverflow Avatar answered Sep 30 '22 19:09

fredoverflow