Problem Statement:
Given an array containing only 0s, 1s and 2s, sort the array in ascending order.
My Approach:
1.First I used technique that used nested loops to sort the array. First loop selects one element. Second loop compares it with remaining elements.
2.If the current element is greater, I swap both elements, I repeat this until the array is sorted.
3.Finally, the array becomes 0s, then 1s, then 2s.I used three pointers l, m, and h. but It just a brute-force technique so test case is not passed.
4.Then I find Dutch National Flag Algorithm Technique.
5.Using that algorithm, l is for 0s, m is current index, and h is for 2s.
6.I traverse the array using m.
7.If element is 0, swap with l and move l and m.
8.If element is 1, move m.
9.If element is 2, swap with h and move h.
10.It's going to repeat until m <= h.
This sorts the array in one pass.
Methods Used:
1.Dutch National Flag Algorithm.

Top comments (0)