0
0
CProgramBeginner · 2 min read

C Program to Sort Characters in String

You can sort characters in a string in C by using a simple nested loop to compare and swap characters, like for (int i = 0; str[i] != '\0'; i++) for (int j = i + 1; str[j] != '\0'; j++) if (str[i] > str[j]) { char temp = str[i]; str[i] = str[j]; str[j] = temp; }.
📋

Examples

Inputhello
Outputehllo
Inputprogramming
Outputaggimmnoprr
Inputa
Outputa
🧠

How to Think About It

To sort characters in a string, think of the string as a list of letters. You compare each letter with the others and swap them if they are out of order. Repeat this until all letters are arranged from smallest to largest based on their ASCII values.
📐

Algorithm

1
Get the input string from the user.
2
Use two loops to compare each character with the others.
3
If a character is greater than the next one, swap them.
4
Repeat until the entire string is sorted.
5
Print the sorted string.
💻

Code

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

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';

    int len = strlen(str);
    for (int i = 0; i < len - 1; i++) {
        for (int j = i + 1; j < len; j++) {
            if (str[i] > str[j]) {
                char temp = str[i];
                str[i] = str[j];
                str[j] = temp;
            }
        }
    }

    printf("Sorted string: %s\n", str);
    return 0;
}
🔍

Dry Run

Let's trace the string "hello" through the code to see how characters are sorted.

1

Initial string

str = "hello"

2

Compare 'h' with 'e', 'l', 'l', 'o'

'h' > 'e' is true, swap -> str = "ehllo"

3

Compare 'e' with 'l', 'l', 'o'

'e' < 'l', no swap

4

Compare first 'l' with second 'l' and 'o'

No swaps needed

5

Final sorted string

str = "ehllo"

IterationString State
Starthello
Swap h and eehllo
No swap e and lehllo
No swap l and lehllo
No swap l and oehllo
💡

Why This Works

Step 1: Reading input

The program reads the string and removes the newline character using fgets and strcspn.

Step 2: Nested loops for comparison

Two loops compare each character with all characters after it to find if any are smaller.

Step 3: Swapping characters

If a character is greater than a later one, they are swapped to move smaller characters forward.

Step 4: Output sorted string

After all swaps, the string is sorted and printed.

🔄

Alternative Approaches

Using qsort from stdlib.h
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int cmpfunc(const void *a, const void *b) {
    return (*(char *)a - *(char *)b);
}

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';

    qsort(str, strlen(str), sizeof(char), cmpfunc);

    printf("Sorted string: %s\n", str);
    return 0;
}
This method uses the built-in quicksort function for better performance and cleaner code.
Bubble sort approach
c
#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';

    int len = strlen(str);
    for (int i = 0; i < len - 1; i++) {
        for (int j = 0; j < len - i - 1; j++) {
            if (str[j] > str[j + 1]) {
                char temp = str[j];
                str[j] = str[j + 1];
                str[j + 1] = temp;
            }
        }
    }

    printf("Sorted string: %s\n", str);
    return 0;
}
This uses bubble sort logic, which is simple but less efficient for large strings.

Complexity: O(n^2) time, O(1) space

Time Complexity

The nested loops compare each character with others, resulting in O(n^2) time where n is string length.

Space Complexity

Sorting is done in-place, so no extra memory beyond the input string is needed, O(1) space.

Which Approach is Fastest?

Using qsort is faster (average O(n log n)) than manual nested loops (O(n^2)) especially for longer strings.

ApproachTimeSpaceBest For
Nested loops swapO(n^2)O(1)Small strings, simple code
Bubble sortO(n^2)O(1)Educational, easy to understand
qsort from stdlib.hO(n log n)O(1)Large strings, performance
💡
Use qsort from stdlib.h for faster and cleaner sorting of characters.
⚠️
Forgetting to remove the newline character after using fgets causes unexpected results.