C Program to Sort Characters of a String

Here is a C program to sort characters of a string. We will sort the characters of string on the basis of ASCII value of characters.

For Example
If input string is "TECHCRASHCOURSE"
Output string should be "ACCCEEHHORRSSTU"


C program to sort the characters of a string

In this program, we are going to use counting sort algorithm which sorts numbers in given range in linear time. This algorithm uses an extra array to count the frequency of each character of string.

We first take a string as input from user using gets function. Then it calls a user defined function 'sortString' that takes input and output array as input and stores the sorted array in output array. Function sortString count the frequency of characters and store it in counterArray integer array. We populate the outputArray in alphabetical order based on the character's frequency in counterArray. At last we add a null character at the end of outputArray.

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

void sortString(char* inputString, char* outputArray);
int main(){
    char inputString[100], outputArray[100];
    
    printf("Enter a String \n");
    gets(inputString);
    
    sortString(inputString, outputArray);
    printf("Sorted string \n%s", outputArray);

    return 0;
}

void sortString(char* inputString, char* outputArray){
    int counterArray[256] ={0}, length, counter, index;
    length = strlen(inputString);
    
    for(counter = 0; counter < length; counter++){
        counterArray[inputString[counter]]++;
    }
    
    for(counter = 0, index = 0; counter < 256; counter++){
        if(counterArray[counter] != 0){
            while(counterArray[counter] > 0){
                outputArray[index++] = counter;
                counterArray[counter]--;
            }
        }
    }
    outputArray[index] = '\0';
}
Output
Enter a String
TECHCRASHCOURSE
Sorted string
ACCCEEHHORRSSTU
Enter a String
london
Sorted string
dlnnoo

Related Topics
C program to compare two strings
C program to concatenate strings
C program to check string is palindrome
C program to remove vowels from a string
C program to remove extra spaces from string
C Program to find frequency of characters in a string
C program to convert lowercase string to uppercase
List of all C programs