Problem
For this problem, your goal is to sort an array of 0
, 1
, 2
but you must do this in place, in linear time and without any extra space (such as creating an extra array). This is called the Dutch national flag sorting problem. For example, if the input array is [2,0,0,1,2,1]
then your program should output [0,0,1,1,2,2]
and the algorithm should run in O(n)
time.
The solution to this algorithm will require 3 pointers to iterate throughout the array, swapping the necessary elements.
- Create a low pointer at the beginning of the array and a high pointer at the end of the array.
- Create a mid pointer that starts at the beginning of the array and iterates through each element.
- If the element at
arr[mid]
is a2
, then swaparr[mid]
andarr[high]
and decrease the high pointer by1
. - If the element at
arr[mid]
is a0
, then swaparr[mid]
andarr[low]
and increase the low and mid pointers by1
. - If the element at
arr[mid]
is a1
, don’t swap anything and just increase the mid pointer by1
.
function swap(arr, i1, i2) {
var temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}
function dutchNatFlag(arr) {
var low = 0;
var mid = 0;
var high = arr.length - 1;
// one pass through the array swapping
// the necessary elements in place
while (mid <= high) {
if (arr[mid] === 0) { swap(arr, low++, mid++); }
else if (arr[mid] === 2) { swap(arr, mid, high--); }
else if (arr[mid] === 1) { mid++; }
}
return arr;
}
dutchNatFlag([2,2,2,0,0,0,1,1]);