Suppose we have an array of Numbers that contains any frequency of exactly three elements - 1, 0 and 1 like this −
const arr = [1, 1, 0, -1, 1, 0, -1, 1, 0, 0, 1];
We are required to write a JavaScript function that takes in one such array. The function should simply sort this special array in place i.e., without using any extra array to store the values.
The only condition is that our function should be a linear time function (using only one iteration).
Example
Following is the code −
const arr = [1, 1, 0, -1, 1, 0, -1, 1, 0, 0, 1]; const sortSpecialArray = (arr = []) => { const swap = (a, b) => { let middle = arr[a] arr[a] = arr[b] arr[b] = middle }; let left = 0; let middle = 0; let right = arr.length-1; while(middle <= right){ if(arr[middle] === -1){ swap(left++, middle++); }else if(arr[middle] === 0){ middle++; }else if(arr[middle] === 1){ swap(right--, middle); } }; }; sortSpecialArray(arr); console.log(arr);
Output
Following is the console output −
[ -1, -1, 0, 0, 0, 0, 1, 1, 1, 1, 1 ]