Open In App

Sorting an Array of Binary Values using JavaScript

JavaScript allows us to sort an array containing only binary values i.e. 0 and 1, below is an example to understand the problem.

Example:

Input 
array = [ 0 , 1, 0, 0 , 0, 1, 0 , 1, 0 , 1, 1]
Output
array = [ 0 , 0 , 0 , 0 , 0, 0 , 1 , 1, 1, 1]

Below are several approaches to sorting an array of binary values using JavaScript which are as follows:

Using sort function

JavaScript has an inbuilt array.sort() function to sort the input array.

Example : To demonstrate Sorting an array of binary values using the inbuilt sort() function

function sortBinaryArray(arr) {
    arr.sort((a, b) => a - b);
    return arr;
}

const binaryArray = [1, 0, 1, 0, 1, 0, 0, 1];
console.log(sortBinaryArray(binaryArray)); 

Output
[
  0, 0, 0, 0,
  1, 1, 1, 1
]

Time complexity: O(n log n)

Space complexity: O(1)

Partitioning algorithm

We will use the concept of the Dutch National Flag algorithm (a partitioning algorithm) to sort an array of binary values. We Set three pointers: low, high, and i. Iterate through the array with i, comparing each element: If it's 0, swap it with array[low] and increment both i and low. If it's 1, just increment i. If it's 2, swap it with array[high] and decrement high. Continue until i exceed high. The array will be sorted in place with 0s at the beginning and 1s at the end.

Example : To demonstrate Sorting an array of binary values using a partitioning algorithm.

function sortBinaryArray(arr) {
    let low = 0;
    let high = arr
        .length - 1;
    let i = 0;

    while (i <= high) {
        if (arr[i] === 0) {
            // Swap arr[i] and arr[low], 
            // increment both i and low
            [arr[i], arr[low]] = [arr[low], arr[i]];
            i++;
            low++;
        } else if (arr[i] === 1) {
            // Increment only i
            i++;
        } else {
            // Swap arr[i] and arr[high],
            //  decrement high
            [arr[i], arr[high]] = [arr[high], arr[i]];
            high--;
        }
    }
}

let binaryArray = [1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0];
sortBinaryArray(binaryArray);
console.log("Sorted Binary Array:", binaryArray);

Output
Sorted Binary Array: [
  0, 0, 0, 0, 0, 0,
  0, 0, 1, 1, 1, 1,
  1, 1, 1
]

Time Complexity: O(n)

Space Complexity: O(1)

Article Tags :