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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

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

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to sort a vector that consists of only 0s and 1s in C++

1 Answer

0 votes
#include <iostream>
#include <vector>

// Function to sort a vector containing only 0s and 1s
void sortBinaryVector(std::vector<int>& arr) {
    int left = 0;               // Index to track the left side
    int right = arr.size() - 1; // Index to track the right side

    while (left < right) {
        // If the left Index is at 0, move it forward
        if (arr[left] == 0) {
            std::cout << "left: " << left << "\n";
            left++;
        }
        // If the right Index is at 1, move it backward
        else if (arr[right] == 1) {
            std::cout << "right: " << right << "\n";
            right--;
        }
        // If left is 1 and right is 0, swap them
        else {
            std::swap(arr[left], arr[right]);
            std::cout << "swap() left: " << left << " " << "right: " << right << "\n";
            left++;
            right--;
        }
    }
}

int main() {
    // Input: Binary vector
    std::vector<int> arr = {1, 0, 1, 0, 1, 0, 0, 1, 0};

    // Sort the binary vector
    sortBinaryVector(arr);

    // Output the sorted vector
    std::cout << "Sorted vector: ";
    for (int num : arr) {
        std::cout << num << " ";
    }
}



/*
run:

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

*/

 



answered Sep 1, 2025 by avibootz
...