📍🔥Advanced

Sort a 2D Array of Strings

Sort string array

Sort a 2D array of strings alphabetically using bubble sort.

Program Code

sort_2d_strings.c
C
1#include <stdio.h>
2#include <string.h>
3
4int main() {
5 char names[][20] = {"Zebra", "Apple", "Mango", "Banana", "Orange"};
6 int n = 5;
7
8 printf("Before sorting:\n");
9 for (int i = 0; i < n; i++) {
10 printf("%s\n", names[i]);
11 }
12
13 // Bubble sort for strings
14 for (int i = 0; i < n - 1; i++) {
15 for (int j = 0; j < n - i - 1; j++) {
16 if (strcmp(names[j], names[j + 1]) > 0) {
17 // Swap strings
18 char temp[20];
19 strcpy(temp, names[j]);
20 strcpy(names[j], names[j + 1]);
21 strcpy(names[j + 1], temp);
22 }
23 }
24 }
25
26 printf("\nAfter sorting:\n");
27 for (int i = 0; i < n; i++) {
28 printf("%s\n", names[i]);
29 }
30
31 return 0;
32}
Output

Before sorting:

Zebra

Apple

Mango

Banana

Orange

 

After sorting:

Apple

Banana

Mango

Orange

Zebra