Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.0 kB
0
Indexable
Never
#include <stdio.h>

void f2(int a[], int n);
void f3(int a[], int n);

int main()
{

    void f2();
    void f3();


}


void f2(int a[], int n)
{
    int count[4] = { 0 }; // An array to keep track of how many times each number appears in the array

    // Counting the occurrences of each number in the array
    for (int i = 0; i < n; i++) {
        count[a[i]]++;
    }

    // Filling the array in the appropriate order
    int index = 0;
    for (int j = 0; j <= 3; j++) {
        for (int k = 0; k < count[j]; k++) 
        {
            a[index++] = j;
        }
    }
}

void f3(int a[], int n) // This function takes an array and its length as input parameters
{
    int i, j, temp; // Declare three integer variables i, j, and temp

    // First pass: move all 0s to the front of the array
    j = 0; // Set j to 0 to keep track of the index of the first non-zero element
    for (i = 0; i < n; i++) { // Iterate over the array
        if (a[i] == 0) { // If the element is 0
            temp = a[i]; // Swap the element with the first non-zero element
            a[i] = a[j];
            a[j] = temp;
            j++; // Move the index of the first non-zero element
        }
    }

    // Second pass: move all 1s after the 0s
    for (i = j; i < n; i++) { // Iterate over the remaining elements in the array
        if (a[i] == 1) { // If the element is 1
            temp = a[i]; // Swap the element with the first non-one element
            a[i] = a[j];
            a[j] = temp;
            j++; // Move the index of the first non-one element
        }
    }

    // Third pass: move all 2s after the 1s
    for (i = j; i < n; i++) { // Iterate over the remaining elements in the array
        if (a[i] == 2) { // If the element is 2
            temp = a[i]; // Swap the element with the first non-two element
            a[i] = a[j];
            a[j] = temp;
            j++; // Move the index of the first non-two element
        }
    }
}