如何对与Score相关联的学生ID数组实施Counting Sort

时间:2018-03-18 04:21:40

标签: c sorting pseudocode

我有一系列学生证和各自的分数。 学生ID已排序。我试图对得分进行排序并获得最终排序位置。如何将学生证移动到最终位置? 排序后得到的输出是

struct SResult sample[] = {
    {"A1234", 10},
    {"A1239", 5},
    {"A1394", 7},
    {"A1434", 3},
    {"A1454", 5},
    {"A2884", 7},
    {"A3235", 7},
    {"A4334", 9},
    {"A4884", 2},
    {"A6934", 5},
    {"A7265", 7},
    {"A9559", 3}
};

我试图实现计数排序算法,排序的输出是

[, 3]
[   , 1]
[
, 5]
[, 0]
[, 0]
[, 0]
[, 0]
[, 0]
[, 0]
[, 0]
[, 0]
[, 0]

#define MAX_SCORE 1000


void counting_sort(struct SResult scoreArr[], int N, int final[]) {
    int freq[MAX_SCORE + 1] = {0}, cfreq[MAX_SCORE + 1] = {0};
    int i, curScore;

    //1. Compute Frequency
    for (i = 0; i < N; i++){
        freq[ scoreArr[i].score ] ++;
    }

    //2. Compute Cumulative Frequency
    cfreq[0] = freq[0];
    for (i = 1; i < N; i++){
        cfreq[i] = cfreq[i - 1] + freq[i];
    }

    //3. Produce Final Position
    for (i = 0; i < N; i++) {
        curScore = scoreArr[i].score;
        final[ cfreq[ curScore ] - 1 ] = i;
        cfreq[curScore]--;
    }
}

0 个答案:

没有答案