简体   繁体   中英

C - Sorting numbers with names attached

I'm a programming beginner can someone help me with this question? This code is for bulls and cows game and I need to do the hall of fame of the guesses made. The hall of fame need to have also the name of the played entered before.

for (b = 0; b < ch - 1; b++) {
    for (c = 0; c < ch - b - 1; c++) {
        if (array[c] > array[c + 1]) {
            sort = array[c];
            array[c] = array[c + 1];
            array[c + 1] = sort;
            //sorting the guessing result in ascending order
        }
    }
}
//printing to a file
printf("Sorted list in ascending order:\n");

for (b = 0; b < ch; b++)
    printf("%d\n", array[b]);

fprintf(file, "Sorting: %s %d\n", user_name, ch);
fclose(file);

An easy way to sort "numbers with attached names" is to put the number and name into a struct and have an array of this struct . Then simply use the standard qsort function for sorting the array.

That could look like this:

#include <stdio.h>
#include <stdlib.h>

// Define a type to hold the score together with the name of the player
typedef struct
{
    char name[42];
    int score;
} PlayerStats;

// Make a compare function to be used by qsort
int cmpfunc (const void * a, const void * b){
    const PlayerStats* pA = a;
    const PlayerStats* pB = b;
    if (pA->score > pB->score) return -1;
    if (pA->score < pB->score) return 1;
    return 0;
}

// A function for printing the players and their score
void print_stats(PlayerStats *ps, size_t n)
{
    for(size_t i=0; i<n; ++i) printf("%s : score=%d\n", ps[i].name, ps[i].score);
}

int main(){
    // Make an array of players with scores.
    PlayerStats player_stats[3] = {{"p1", 17}, {"p2", 9}, {"p3", 42}};
    size_t numElements = sizeof player_stats / sizeof player_stats[0];
    size_t sizeElement = sizeof player_stats[0];

    printf("Unsorted:\n");
    print_stats(player_stats, numElements);

    // Use the standard qsort for sorting the array
    qsort(player_stats, numElements, sizeElement, cmpfunc);

    printf("Sorted:\n");
    print_stats(player_stats, numElements);

    return 0;
}

Output:

Unsorted:
p1 : score=17
p2 : score=9
p3 : score=42
Sorted:
p3 : score=42
p1 : score=17
p2 : score=9

Try it here: https://ideone.com/HMgDbn

If you want ascending sort you simply change the compare function like:

int cmpfunc (const void * a, const void * b){
    const PlayerStats* pA = a;
    const PlayerStats* pB = b;
    if (pA->score > pB->score) return 1;   // Change -1 to 1
    if (pA->score < pB->score) return -1;  // Change 1 to -1
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM