Problem solving with programming: Sorting the array of 0,1,2's
We have an array that contains only 0, 1 and 2. We have to write a program to sort this array.For example if the input array is [2,0,1,2,1,0,0,2], the output should be
[0,0,0,1,1,2,2,2].
As the first thought, we can very well use well known sorting algorithms like Quick sort, or Merge sort or Heap sort. But that would be an overkill to solve this problem. We can utilize the property that the array contains just 0,1, and 2.
Method#1: Bucket sort approach - Simple
Just take three counters to count 0,1 and 2. Update these while iterating through the array. This is an example of bucket sort with three buckets. Every time we see a 0, we put that in 0th bucket. If we see a 1 we put that into a 1st bucket and so on...
In the second iteration, Fill the array with respective counts of 0,1, and 2 in that order. The following is the Java implementation.
Read full article from Problem solving with programming: Sorting the array of 0,1,2's
No comments:
Post a Comment