Untitled

 avatar
unknown
c_cpp
a year ago
817 B
9
Indexable
// Online C compiler to run C program online
#include <stdio.h>

int main() {
    int unsorted[] = {2, 3, 0, 2, 3, 2};
    int len = 6;
    
    // find the max value
    int maxValue = unsorted[0];
    for (int i = 1; i < len; i++) {
        if (maxValue < unsorted[i]) {
            maxValue = unsorted[i];
        }
    }
    
    // count frequency for each value
    int count[maxValue + 1];
    for (int i = 0; i < len; i++) {
        count[unsorted[i]]++;
    }
    
    // add required number of each values in the sorted array
    int sorted[len];
    for (int i = 0, j = 0; i <= maxValue; i++) {
        while (count[i] > 0) {
            sorted[j] = i;
            j++;
            count[i]--;
        }
    }
    
    for (int i = 0; i < len; i++) {
        printf("%d ", sorted[i]);
    }
    return 0;
}
Editor is loading...
Leave a Comment