To sort a string array in dictionary order in C, you can use the bubble sort algorithm or any other sorting algorithm. The sorting is performed by comparing each string with the others and swapping them if they are out of order.
In this example,
arr
.n
to specify the number of elements in the array.n-1
times, and the inner loop runs from 0 to n-i-1
to compare adjacent elements.#include <stdio.h>
#include <string.h>
void swap(char *str1, char *str2) {
char temp[100];
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
}
void sortStringArray(char arr[][100], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (strcmp(arr[j], arr[j+1]) > 0) {
swap(arr[j], arr[j+1]);
}
}
}
}
int main() {
char arr[][100] = {"pear", "apple", "orange", "banana"};
int n = sizeof(arr) / sizeof(arr[0]);
sortStringArray(arr, n);
printf("Sorted array: \n");
for (int i = 0; i < n; i++) {
printf("%s\n", arr[i]);
}
return 0;
}
Sorted array: apple banana orange pear
In this example,
arr
.n
to specify the number of elements in the array.n-1
times, and the inner loop runs from 0 to n-i-1
to compare adjacent elements.#include <stdio.h>
#include <string.h>
void swap(char *str1, char *str2) {
char temp[100];
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
}
void sortStringArray(char arr[][100], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (strcmp(arr[j], arr[j+1]) > 0) {
swap(arr[j], arr[j+1]);
}
}
}
}
int main() {
char arr[][100] = {"zebra", "apple", "mango", "cherry"};
int n = sizeof(arr) / sizeof(arr[0]);
sortStringArray(arr, n);
printf("Sorted array: \n");
for (int i = 0; i < n; i++) {
printf("%s\n", arr[i]);
}
return 0;
}
Sorted array: apple cherry mango zebra
In this tutorial, we learned How to Sort a String Array in Dictionary Order in C language with well detailed examples.