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,970 questions

51,912 answers

573 users

How to sort an array that consists of only 0s and 1s in C

1 Answer

0 votes
#include <stdio.h>

// Function to sort an array containing only 0s and 1s
void sortBinaryArray(int arr[], int size) {
    int left = 0;               // Index to track the left side
    int right = 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) {
            printf("left: %d\n", left);
            left++;
        }
        // If the right Index is at 1, move it backward
        else if (arr[right] == 1) {
            printf("right: %d\n", right);
            right--;
        }
        // If left is 1 and right is 0, swap them
        else {
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            printf("swap() left: %d right: %d\n", left, right);
            left++;
            right--;
        }
    }
}

int main() {
    // Input: Binary array
    int arr[] = {1, 0, 1, 0, 1, 0, 0, 1, 0};
    int size = sizeof(arr) / sizeof(arr[0]);

    // Sort the binary array
    sortBinaryArray(arr, size);

    // Output the sorted array
    printf("Sorted array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}



/*
run:

swap() left: 0 right: 8
left: 1
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 

*/




answered Sep 1, 2025 by avibootz
...