We need to take three-pointers, low, mid, high. We will use low and mid pointers at the start, and the high pointer will point at the end of the given array.
If array [mid] =0, then swap array [mid] with array [low] and increment both pointers once.
If array [mid] = 1, then no swapping is required. Increment mid pointer once.
If array [mid] = 2, then we swap array [mid] with array [high] and decrement the high pointer once.
Time complexity − O(N)
Example
using System;
namespace ConsoleApplication{
public class Arrays{
private void Swap(int[] arr, int pos1, int pos2){
int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
public void DutchNationalFlag(int[] arr){
int low = 0;
int mid = 0;
int high = arr.Length - 1;
while (mid <= high){
if (arr[mid] == 0){
Swap(arr, low, mid);
low++;
mid++;
}
else if (arr[mid] == 2){
Swap(arr, high, mid);
high--;
}
else{
mid++;
}
}
}
}
class Program{
static void Main(string[] args){
Arrays a = new Arrays();
int[] arr = { 2, 1, 1, 0, 1, 2, 1, 2, 0, 0, 1 };
a.DutchNationalFlag(arr);
for (int i = 0; i < arr.Length; i++){
Console.WriteLine(arr[i]);
}
Console.ReadLine();
}
}
}Output
0 0 0 0 1 1 1 1 2 2 2