C Program to Sort a String of Characters (original) (raw)

Last Updated : 05 Dec, 2024

Sorting a string of characters refers to the process of rearranging all the characters in the given order. In this article, we will learn how to sort a string of characters using the C program.

The most straightforward method to sort a string of characters is by using the **qsort() function. Let's take a look at an example:

C `

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

// Comparator function for qsort int comp(const void *a, const void b) { return ((char *)a - *(char *)b);
}

int main() { char s[] = "adfecb";

// Sort the string using qsort
qsort(s, strlen(s), sizeof(char), comp);

printf("%s", s);
return 0;

}

`

**Explanation: The qsort() function needs a comparator that guides it how to compare two values of the given dataset. In this case, it tells how two characters should be compared and the order in which they should be arranged.

C language only provides the built-in method for the quick sort algorithm. If you need any other sorting algorithm, you will have to implement them yourself as shown:

Using Bubble Sort

**Bubble Sort is a simple comparison-based sorting algorithm which repeatedly compares adjacent characters and swaps them if they are in the wrong order.

C `

#include <stdio.h>

// Implementation of bubble sort void bubbleSort(char *s) { int n = 0; while (s[n] != '\0') n++; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (s[j] > s[j + 1]) { char temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; } } } }

int main() { char s[] = "adfecb";

// Sort the string using Bubble Sort
bubbleSort(s);

printf("%s", s);
return 0;

}

`

**Using Selection Sort

**Selection Sort is another comparison-based sorting algorithm that works by finding the smallest character from the unsorted portion of the string and swapping it with the first unsorted character. This process is repeated until the entire string is sorted.

C `

#include <stdio.h>

// Implementation of selection sort void selSort(char *s) { int n = 0; while (s[n] != '\0') n++; for (int i = 0; i < n - 1; i++) { int minIndex = i; for (int j = i + 1; j < n; j++) { if (s[j] < s[minIndex]) { minIndex = j; } } char temp = s[minIndex]; s[minIndex] = s[i]; s[i] = temp; } } int main() { char s[] = "adfecb";

  // Sort the string using Selection Sort
selSort(s);

printf("%s", s);
return 0;

}

`