C Online Compiler
Example: String Sorting using Bubble Sort in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// String Sorting using Bubble Sort #include <stdio.h> #include <string.h> // For strcmp and strcpy int main() { // Step 1: Define the array of strings to be sorted char strings[][20] = {"banana", "apple", "cherry", "date", "grape"}; int n = sizeof(strings) / sizeof(strings[0]); // Calculate number of strings char temp[20]; // Temporary buffer for swapping strings printf("Original strings:\n"); for (int i = 0; i < n; i++) { printf("%s\n", strings[i]); } printf("\n"); // Step 2: Implement Bubble Sort // Outer loop for passes for (int i = 0; i < n - 1; i++) { // Inner loop for comparisons and swaps in each pass for (int j = 0; j < n - i - 1; j++) { // Compare adjacent strings using strcmp // strcmp returns < 0 if first string is smaller, > 0 if larger, 0 if equal if (strcmp(strings[j], strings[j + 1]) > 0) { // If strings[j] is alphabetically greater than strings[j+1], swap them strcpy(temp, strings[j]); // Copy strings[j] to temp strcpy(strings[j], strings[j + 1]); // Copy strings[j+1] to strings[j] strcpy(strings[j + 1], temp); // Copy temp to strings[j+1] } } } // Step 3: Print the sorted strings printf("Sorted strings (Bubble Sort):\n"); for (int i = 0; i < n; i++) { printf("%s\n", strings[i]); } return 0; }
Output
Clear
ADVERTISEMENTS