menu
techminis

A naukri.com initiative

google-web-stories
Home

>

Programming News

>

Sort Colors In Place
source image

Prodevelopertutorial

2w

read

346

img
dot

Sort Colors In Place

  • The problem here is ‘sort an array of 0s, 1s and 2s’ when given an array of unsorted 0’s, 1’s and 2’s. We can solve this problem in an integer array by simple counting the number of 0’s, 1’s, and 2’s present in the array and placing them again each other , which is also called Counting Sort
  • In this solution, we take 3 variables [n0, n1, n2] and set them to “-1”. We start iterating from the first element of the array. If the element is “0” then increment the index of all the 3 variables [n0, n1, n2], and place the appropriate value.
  • If the element is “1” then increment the index of 2 variables [n1, n2], and place the appropriate value. If the element is “2” then increment the index of n2, and place the appropriate value.
  • In another solution, we take 3 pointers low, mid, high. From the input, we know that mid is “1”, and the elements lesser than mid will be swapped to the left of mid, and the elements greater than mid, will be pushed to the right of mid.
  • This solution can also be solved using Dutch National Flag Algorithm, which maintains 3 pointers - low, mid and high and swaps the values according to their values without using any if-else statements or extra memory space.
  • Sorting an array of 0's, 1's and 2's is a classical computer science problem and is popularly called the Dutch national flag problem.
  • The solution can be implemented using simple techniques like counting the number of 0’s, 1’s, and 2’s; In-place method using 3 pointers and another using Dutch national flag algorithm.
  • All the techniques are optimal solutions to the problem and take linear time to sort the array.
  • Given an array of size n containing only 0s, 1s, and 2s; sort the array in ascending order.
  • Return the sorted array. You are not allowed to use sorting libraries.

Read Full Article

like

20 Likes

For uninterrupted reading, download the app