We need three-pointers, low, mid, and high. We will use low and mid pointers at the beginning and high pointer will point to the end of the given array.
If array [mid] =0, swap array [mid] with array [low]] and increment both pointers once.
If array [mid] = 1, no exchange is required. Increment the middle pointer once.
If array [mid] = 2, swap array [mid] with array [high] and decrement the high pointer once.
Time complexity - O(N)
Real-time demonstration
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(); } } }
0 0 0 0 1 1 1 1 2 2 2
The above is the detailed content of How to sort 0,1,2 in an array (Dutch flag) without extra space using C#?. For more information, please follow other related articles on the PHP Chinese website!