Isaac101
Isaac101

Reputation: 65

C programming: How to sort an array in an ascending order

for (c = 0; c < 26; c++) {
    for (d = c + 1; d < 26; d++) {
        if (count[c] > count[d]) {
            tem = count[c];
            count[c] = count[d];
            count[d] = tem;

            printf("%c: %d\n", c + 'a', count[c]);
        }
    }
}

I am trying to sort an array in ascending order. I tried to get help from already answered questions, but they all did not work for me.

My code:

  1. User inputs a lowercase characters
  2. program prints out each character in ascending order (e.g. input: ggggllppp output: l-2 p-3 g-4)

What is wrong with my code?

Upvotes: 0

Views: 956

Answers (1)

जलजनक
जलजनक

Reputation: 3071

Make use of a structure to store both ASCII value & count of a character in the string. Once you've all the counts, sort the structures based on the counts.

Alter the print statement to your liking.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int ascii;
    int count;
} azCount_t;


int cmp(const void *p, const void *q) {
    return (((azCount_t*)p)->count > ((azCount_t*)q)->count);
}

int main (void) {
    char str [] = "program prints out each character in ascending order (e.g. input: ggggllppp output: l-2 p-3 g-4)";
    int slen = strlen (str);
    azCount_t acs [256] = {0};
    // Initialising the structure with ascii codes
    for (int ci = 0; ci < 256; ++ci)
        acs [ci].ascii = ci;    //ascii index
    // counting the occurrences of chars in input string
    for (int si = 0; si < slen; )
        ++acs[(unsigned char)str[si++]].count;

    //sort based on count ascedning order
    qsort (acs, 256, sizeof(azCount_t), cmp);

    printf ("Character Counts in string:\n[%s]\n", str);
    for (int ai = 0; ai < 256; ++ai)
        if (acs[ai].count)
            printf ("[%c] - %d\n", acs[ai].ascii, acs[ai].count);

    printf ("\n");
    return 0;
}

Upvotes: 2

Related Questions