I have been trying to make this program sort a 2d array of strings by column index.
I initialized this 2d array like this:
char *str[ROWS][COLS] = {{"Russia", "Boxing", "Mens", "Gold"},
{"America", "Cycling", "Mens", "Gold"},
{"New Zealand", "Swimming", "Womens", "Silver"},
{"India", "Badminton", "Mens", "Bronze"}};
And if I wanted to sort this array by the first column, the country names, then it would look something like this:
char *str[ROWS][COLS] = {{"America", "Cycling", "Mens", "Gold"},
{"India", "Badminton", "Mens", "Bronze"}};
{"New Zealand", "Swimming", "Womens", "Silver"},
{"Russia", "Boxing", "Mens", "Gold"}};
This is what I have done so far, and it is nearly correct, except for the sorting method. I am having trouble implementing that.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ROWS 4
#define COLS 4
void print_array(char *str[][COLS]);
void sort_array(char *str[][COLS], int nrows, int col);
int
main(void) {
char *str[ROWS][COLS] = {{"Russia", "Boxing", "Mens", "Gold"},
{"America", "Cycling", "Mens", "Gold"},
{"New Zealand", "Swimming", "Womens", "Silver"},
{"India", "Badminton", "Mens", "Bronze"}};
int col;
/* array before sorting */
printf("Before: \n");
print_array(str);
/*choosing column index to sort by*/
printf("\nChoose which column index you wish to sort by: ");
if (scanf("%d", &col) != 1) {
printf("Invalid input\n");
exit(EXIT_FAILURE);
}
sort_array(str, ROWS, col);
/* array after sorting */
printf("\nAfter: \n");
print_array(str);
return 0;
}
void
print_array(char *str[][COLS]) {
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
printf("%s ", str[i][j]);
}
printf("\n");
}
}
/*function used for sorting the array */
void
sort_array(char *str[][COLS], int nrows, int col) {
int i, j;
char *temp;
for (i = 0; i < nrows; i++) {
for (j = i; j < nrows; j++) {
if(strcmp(str[i][col], str[j][col]) > 0) {
temp = str[i][col];
str[i][col] = str[j][col];
str[j][col] = temp;
}
}
}
}
The issue I'm having is that my sorting algorithm is not swapping the rows, but the just strings in that column. I was also trying to use the insertion sort algorithm but I was not sure how to implement that with a 2d array of strings.
Any help would be appreciated :)