C Online Compiler
Example: Sort String Descending (Selection Sort) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Sort String Descending (Selection Sort) #include <stdio.h> #include <string.h> // Required for strlen() int main() { char str[] = "programming"; int length = strlen(str); int i, j, max_idx; char temp; printf("Original string: %s\n", str); // Step 1: Outer loop iterates through each position to place an element for (i = 0; i < length - 1; i++) { // Step 2: Assume the current element is the maximum max_idx = i; // Step 3: Inner loop finds the actual maximum element in the unsorted part for (j = i + 1; j < length; j++) { // Step 4: If a larger element is found, update max_idx if (str[j] > str[max_idx]) { max_idx = j; } } // Step 5: If the maximum element is not at the current position 'i', swap them if (max_idx != i) { temp = str[i]; str[i] = str[max_idx]; str[max_idx] = temp; } } // Step 6: Print the sorted string printf("Sorted string (descending): %s\n", str); return 0; }
Output
Clear
ADVERTISEMENTS