我无法以正确的方式对这个数组进行排序,我不明白为什么。我想对数组进行排序,但保留原始索引,以便索引可以与我的索引 int 数组与播放器匹配,因此我可以将播放器的名称放在那里。
我得到这样的东西:
before sorting
_________________________________
Players ranked are David Beckham ENG ---- 0.
Players ranked are Wayne Rooney ENG ---- 5.
Players ranked are Pirlo ITA ---- 3.
Players ranked are Del Piero ITA ---- 2.
Players ranked are Lionel Messi ARG ---- 5.
after sorting ( which is wrong )
Players ranked are David Beckham ENG ---- 0.
Players ranked are Wayne Rooney ENG ---- 0.
Players ranked are Pirlo ITA ---- 5.
Players ranked are Del Piero ITA ---- 3.
Players ranked are Lionel Messi ARG ---- 2.
谁能帮我这个 ?
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#define PLAYERS 5
#define NUM_COUNTRIES 3
#define LENGTH_NAME 40
#define LENGTH_CODE 4
#define LENGTH_COUNTRY 20
void sort_func(int array[], char name_and_country_code[][LENGTH_NAME], int elements);
int LocationOfLargest(int array[], int n);
print_array (int array[], char name_and_country_code[][LENGTH_NAME], int elements);
void swap (int *a , int *b);
int main (void)
{
int match1[PLAYERS] = { 0,1,3,2,4};
int match2[PLAYERS] = { 0,4,0,0,1};
int goals[PLAYERS] ;
char name[PLAYERS][LENGTH_NAME] ={"David Beckham","Wayne Rooney","Pirlo", "Del Piero","Lionel Messi"};
char country_abbreviations[PLAYERS][LENGTH_CODE] = {"ENG","ENG","ITA","ITA","ARG"};
char country_code[NUM_COUNTRIES][LENGTH_CODE] = {"ARG","ENG","ITA"};
char country_name[NUM_COUNTRIES][LENGTH_COUNTRY] = {"Argentina", "England","Italy"};
char name_and_country_code[PLAYERS][LENGTH_NAME];
char country_code_and_country_name[NUM_COUNTRIES][LENGTH_COUNTRY];
int i, first =1, second= 2;
for(i=0; i < PLAYERS; i++)
{
strcpy (name_and_country_code[i], name[i]);
strcat (name_and_country_code[i], " " );
strcat (name_and_country_code[i], country_abbreviations[i]);
goals[i]= match1[i] + match2[i];
printf("Player %s----- score %d:\n", name_and_country_code[i], goals[i]);
}
printf("\n_________________________________\n");
//before sorting
print_array ( goals, name_and_country_code, PLAYERS );
printf("\n");
sort_func ( goals, name_and_country_code, PLAYERS);
//after sorting not working right
print_array ( goals, name_and_country_code, PLAYERS );
return 0;
}
print_array (int array[], char name_and_country_code[][LENGTH_NAME], int elements)
{
int i ;
for ( i = 0 ; i < PLAYERS; i ++)
{
printf ("Players ranked are %s ---- %d.\n", name_and_country_code[i], array[i]);
}
}
void sort_func(int array[], char name_and_country_code[][LENGTH_NAME], int elements)
{
int index ,last = elements-1;
while (last >0 )
{
index = LocationOfLargest(array, last);
swap (&array[last], &array [index]);
last--;
}
}
void swap (int *a , int *b)
{
int tmp = *a ;
*a = *b;
*b = tmp;
}
int LocationOfLargest(int array[], int n)
{
int j , index =0 ;
for (j = 0 ; j <= n ; j ++)
if (array[index] < array[j])
index = j;
return j;
}