I want to have a main program that reads 10 names using scanf (maximum 100 characters), saves them to a 2D array (char[10][100]) and then calls a function that has the algorithm of the bubblesort and sorts the 2D array. And finally I want the main program to print the sorted 2D array.
The prototype of the function is:
void bubble_sort(str[][100]);
Can anybody show me the code?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 10
void bubble_sort(char str[SIZE][100]);
int main (void) {
char names[SIZE][100];
int i, j;
for (i = 0; i < SIZE; i++) {
printf("Enter names: ");
scanf("%s", names[i]);
}
bubble_sort(names);
for (int i = 0; i < SIZE; i++)
printf ("%s\n", names[i]);
}
void bubble_sort(char str[SIZE][100]) {
int i, j, reorder = 0;
char temp;
for (i = 1; i < SIZE; i++) {
for (j = SIZE - 1; j >= i; j--) {
if (strcmp(str[j], str[j + 1]) > 0) {
strcpy(temp, str[j + 1]);
strcpy(str[j + 1], str[j]);
strcpy(str[j], temp);
reorder = 1;
}
}
if (reorder == 0)
return;
}
}
I expect to type 10 names and then get as an output these 10 names in an ascending alphabetical way.
for (i = 1; i < SIZE; i++) { for (j = SIZE-1; j <=i; j++)— when does this iterate on the inner loop? You'll also need to revisit when you setreorder = 0;.