Can someone help me with this problem in C? I need to sort leaderboard in alphabetical order and that works, and by scores. I use atoi()
for converting string to integers, but names stay in the order they were left. Here is the function for sorting:
void bubbleSort2(int arr[], int n)
{
int c,d;
int swap;
for (c = 0; c < n - 1; c++)
{
for (d = 0; d < n - c - 1; d++)
{
if (arr[d] < arr[d + 1])
{
swap = arr[d];
arr[d] = arr[d + 1];
arr[d + 1] = swap;
}
}
}
}
void sortScores() {
FILE* fp = openFile();
int x[128];
char line[128][20];
int i = 0, j = 0;
int tot = 0;
while (fgets(line[i], 20, fp))
{
line[i][strlen(line[i]) - 1] = '\0';
i++;
}
tot = i;
for (int i = 0; i < tot; i++)
{
char* sep = strchr(line[i], ' ');
*sep = '\0';
x[i] = atoi(sep + 1);
}
bubbleSort2(x, tot);
printf("Sorted by scores:\n");
for (int i = 0; i < tot; i++)
{
printf("%s %d\n", line[i],x[i]);
}
fclose(fp);
}
Here is the output:
Sorted alphabetical:
Branimir 100
Branimir 700
Brekalo 100
Hrvoje 350
Ilija 0
Ilija 50
Marin 100
Marin 400
Marko 0
Marko 300
Matej 0
Matej 900
Nikola 0
Pero 100
Pero 150
Ramal 100
Simun 550
Skoric 0
Sorted by scores:
Ramal 900
Ilija 700
Ilija 550
Pero 400
Pero 350
Nikola 300
Marko 150
Marin 100
Marko 100
Marin 100
Matej 100
Branimir 100
Matej 50
Branimir 0
Brekalo 0
Skoric 0
Hrvoje 0
Simun 0
Matej should be first in sorted by scores and not Ramal. I hope you could help me with this one.
you are just sorting the values not the names along with it.
Also change the indices of char line[128][20] in the sorting function.
In the main function pass bubbleSort2(x, tot,line)
;
And in the bubble sort
void bubbleSort2(int arr[], int n,char line[128][20])
{
int c,d;
int swap;
for (c = 0; c < n - 1; c++)
{
for (d = 0; d < n - c - 1; d++)
{
if (arr[d] < arr[d + 1])
{
swap = arr[d];
arr[d] = arr[d + 1];
arr[d + 1] = swap;
swap(line[d],line[d+1]);
}
}
}
}
Hope it helps :)