Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,181 questions

56,073 answers

573 users

How to sort an array that consists of only 0s and 1s in Node.js

1 Answer

0 votes
// Function to sort an array containing only 0s and 1s
function sortBinaryArray(arr) {
    let left = 0;                  // Index to track the left side
    let right = arr.length - 1;    // Index to track the right side

    while (left < right) {
        // If the left index is at 0, move it forward
        if (arr[left] === 0) {
            console.log("left: " + left);
            left++;
        }
        // If the right index is at 1, move it backward
        else if (arr[right] === 1) {
            console.log("right: " + right);
            right--;
        }
        // If left is 1 and right is 0, swap them
        else {
            const temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            console.log("swap() left: " + left + " right: " + right);
            left++;
            right--;
        }
    }
}

// Input: Binary array
const arr = [1, 0, 1, 0, 1, 0, 0, 1, 1, 0];

sortBinaryArray(arr);

console.log("Sorted array:", arr.join(" "));




/*
run:

swap() left: 0 right: 9
left: 1
right: 8
right: 7
swap() left: 2 right: 6
left: 3
swap() left: 4 right: 5
Sorted array: 0 0 0 0 0 1 1 1 1 1

*/



 



answered Sep 3, 2025 by avibootz
...