We could have use two way pointer approach if we would have only two values 0s and 1s but we have three 0s, 1s, and 2s, Now we can use the Dutch National Flag algorithm, also known as the 3-way partitioning algorithm. This algorithm separates the array into three sections: 0s, 1s, and 2s.
Here's an example implementation in Java:
javapublic class Sort012 {
public static void sortArray(int[] nums) {
int low = 0;
int mid = 0;
int high = nums.length - 1;
while (mid <= high) {
if (nums[mid] == 0) {
// Swap element at mid with element at low
int temp = nums[low];
nums[low] = nums[mid];
nums[mid] = temp;
low++;
mid++;
} else if (nums[mid] == 1) {
// Move to the next element
mid++;
} else if (nums[mid] == 2) {
// Swap element at mid with element at high
int temp = nums[mid];
nums[mid] = nums[high];
nums[high] = temp;
high--;
}
}
}
public static void main(String[] args) {
int[] nums = {2, 0, 1, 1, 0, 2, 1, 0};
System.out.println("Before sorting: " + Arrays.toString(nums));
sortArray(nums);
System.out.println("After sorting: " + Arrays.toString(nums));
}
}
In this example, the array is {2, 0, 1, 1, 0, 2, 1, 0}
. After sorting the array using the Dutch National Flag algorithm, the sorted array will be {0, 0, 0, 1, 1, 1, 2, 2}
.
The algorithm maintains three pointers: low
, mid
, and high
. The low
pointer keeps track of the boundary of the section with 0s, the mid
pointer scans the array, and the high
pointer keeps track of the boundary of the section with 2s.
The algorithm traverses the array from left to right. If the element at the mid
pointer is 0, it is swapped with the element at the low
pointer, and both pointers are incremented. If the element at the mid
pointer is 1, it is left in its place, and the mid
pointer is incremented. If the element at the mid
pointer is 2, it is swapped with the element at the high
pointer, and the high
pointer is decremented. This process continues until the mid
pointer surpasses the high
pointer, indicating that the array is sorted.