Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting algorithm which does not allow counting of elements

Tags:

java

sorting

I have seen acrosss in a company interview test this question, but i am not clear about the question first. Could you people clarify my doubt ?

Question : Write a program to sort an integer array which contains Only 0's,1's and 2's. Counting of elements not allowed, you are expected to do it in O(n) time complexity.

Ex Array : {2, 0, 1, 2, 1, 2, 1, 0, 2, 0}

like image 697
deepakboppudi Avatar asked Jul 12 '11 07:07

deepakboppudi


People also ask

Why is counting sort not used?

However, counting sort is generally only ever used if k isn't larger than n; in other words, if the range of input values isn't greater than the number of values to be sorted. In that scenario, the complexity of counting sort is much closer to O(n), making it a linear sorting algorithm.

In which sorting algorithm elements are not compared?

Non-comparison based sorting – In non-comparison based sorting, elements of array are not compared with each other to find the sorted array.

What type of algorithm is counting sort?

Counting sort is a sorting algorithm that sorts the elements of an array by counting the number of occurrences of each unique element in the array. The count is stored in an auxiliary array and the sorting is done by mapping the count as an index of the auxiliary array.

Which is not effective sorting algorithm?

On the other hand, shell sort is not as efficient as other sorting algorithms such as quicksort and merge sort.


2 Answers

Output to a linked list.

  • Remember the beginning of the list.
  • Remember the position where the 1s start.
  • Remember the end of the list.

Run through the whole array.

  • If you encounter a 0, add it to the first position of the linked list.
  • If you encounter a 1, add it after the position of the 1.
  • If you encounter a 2, add it at the end of the list.

HTH

Raku

like image 67
Raku Avatar answered Sep 21 '22 01:09

Raku


Instead of blasting you with yet another unintelligible pseudo-code, I’ll give you the name of the problem: this problem is known as the Dutch national flag problem (first proposed by Edsgar Dijkstra) and can be solved by a three-ways merge (see the PHP code in the first answer which solves this, albeit very inefficiently).

A more efficient in-place solution of the threeways merge is described in Bentley’s and McIlroy’s seminal paper Engineering a Sort Function. It uses four indices to delimit the ranges of the intermediate array, which has the unsorted values in the middle, the 1s at both edges, and the 0s and 2s in-between:

threeways merge

After having established this invariant, the = parts (i.e. the 1s) are swapped back into the middle.

like image 40
Konrad Rudolph Avatar answered Sep 19 '22 01:09

Konrad Rudolph