C Online Compiler
Example: Sorting Names using Bubble Sort in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Sorting Names using Bubble Sort #include <stdio.h> #include <string.h> // Required for strcmp and strcpy #define MAX_NAMES 5 #define MAX_LEN 50 int main() { // Step 1: Initialize an array of strings char names[MAX_NAMES][MAX_LEN] = { "Charlie", "Alice", "Bob", "David", "Eve" }; int i, j; // Step 2: Print the original list of names printf("Original names:\n"); for (i = 0; i < MAX_NAMES; i++) { printf("%s\n", names[i]); } printf("\n"); // Step 3: Implement Bubble Sort // Outer loop for passes for (i = 0; i < MAX_NAMES - 1; i++) { // Inner loop for comparisons and swaps in each pass for (j = 0; j < MAX_NAMES - 1 - i; j++) { // Compare adjacent strings using strcmp // strcmp returns < 0 if first string is "less than" (comes before) the second // strcmp returns > 0 if first string is "greater than" (comes after) the second // strcmp returns 0 if strings are equal if (strcmp(names[j], names[j+1]) > 0) { // If names[j] comes after names[j+1] alphabetically, swap them char temp[MAX_LEN]; // Copy names[j] to temp strcpy(temp, names[j]); // Copy names[j+1] to names[j] strcpy(names[j], names[j+1]); // Copy temp to names[j+1] strcpy(names[j+1], temp); } } } // Step 4: Print the sorted list of names printf("Sorted names (Bubble Sort):\n"); for (i = 0; i < MAX_NAMES; i++) { printf("%s\n", names[i]); } return 0; }
Output
Clear
ADVERTISEMENTS