Dutch Flag Algorithm

rahul singh tomar
1 min readMay 23, 2022

This Algorithm is used to sort number in array of 0,1,2 . it is called Dutch algorithm because in dutch flag there are three colors.

In this algorithm we define low , high and mid variable to sort array.

In above code , we have one unsorted array and we have to sort in 0,1,2.

we can use any sorting algorithm to sort this array but for this problem we use dutch algorithm .

In code we made two function one to swap variable and one to sort array.

we use while condition to run code till mid is equal or lesser than high.

if mid element of array is 0 then we swap with low element and add index of both low and mid . same if we found mid element is 2 then we swap with high element and decrease value of high and if mid value is 1 then we add 1 to mid.

at the end we will get sorted array.

  • Time Complexity: O(n).
  • Space Complexity: O(1).

--

--