Efficient Sorting of 0s, 1s and 2s: The Dutch National Flag Problem in JavaScript
The Dutch National Flag problem is a classic problem in computer science that involves sorting an array of 0s, 1s and 2s. The problem is named after the Dutch national flag, which consists of three colors: red, white and blue. The problem can be solved in linear time and constant space by using a two-pointer approach.
Here is an example of a JavaScript function that sorts an array of 0s, 1s and 2s using the Dutch National Flag algorithm:
function dutchNationalFlagSort(arr) {var low = 0;var mid = 0;var high = arr.length - 1;while (mid <= high) {if (arr[mid] === 0) {swap(arr, low, mid);low++;mid++;} else if (arr[mid] === 1) {mid++;} else {swap(arr, mid, high);high--;}}return arr;}function swap(arr, i, j) {var temp = arr[i];arr[i] = arr[j];arr[j] = temp;}console.log(dutchNationalFlagSort([1, 0, 2, 1, 0, 2, 1, 2, 0]));
The above code will output: [0, 0, 0, 1, 1, 1, 2, 2, 2]
Explanation:
The function takes an array as an input, it uses three pointers low
, mid
and high
to partition the array into four regions:
- The region from 0 to low-1 contains only 0s
- The region from low to mid-1 contains only 1s
- The region from mid to high contains unknown elements
- The region from high+1 to the end of the array is empty
The while loop runs until mid
is less than or equal to high
, in each iteration it checks the value of the element at mid
, if it's 0, it swaps the element at mid
with the element at low
, increments low
and mid
by 1. If it's 1, it increments mid
by 1. If it's 2, it swaps the element at mid
with the element at high
and decrements high
by 1. This way it ensures that all the 0s will be at the beginning of the array, all the 1s will be in the middle of the array and all the 2s will be at the end of the array.
Comments
Post a Comment