C ++实现计数排序

时间:2015-04-30 09:12:58

标签: c++ arrays sorting

我正在基于计数排序进行基于非比较的排序。

我在纸上进行了模拟,但实际编码却遇到了麻烦。

我知道我需要创建一个count数组,然后在计数后使用另一个数组累加它然后用它创建一个新数组,使用累积和来对它进行排序。如何让计数数组跟踪?那部分让我困惑

有人能引导我朝正确的方向前进吗?

int schoolToIndex(string school) {
    if (school == "UCB")  return 0;
    if (school == "UCD")  return 1;
    if (school == "UCI")  return 2;
    if (school == "UCLA") return 3;
    if (school == "UCM")  return 4;
    if (school == "UCSD") return 5;
    if (school == "UCSF") return 6;

    cerr << "Unknown school " << school << endl;
    return -1;
}

/*
 * Sorts students by school. An implementation of counting sort.
 * @param students array already sorted by ID
 * @param len Array length
 */
void sortByGroupById2(Student students[], int len) {
    int temp[len];
    int count[7];

    // Creates an array where schools are converted to ints by using schoolToIndex
    for(int i = 0; i < len; i++) {
        temp[i] =schoolToIndex(students[i].getSchool());

    }

    for(int i =0; i < 7;  i++) {
        count[i]=0;
    }


    for(int j =0; j < len;  j++) {
        count[temp[j]]++;
        cout << j << " "  << count[j] << endl;

    }
}
使用

test.txt文件

 Joe Paarmann,10000010,UCSF
Otha Baloy,10000053,UCSD
Alton Hamblet,10000110,UCM
Jessie Merle,10000345,UCI
Lawanda Doell,10000455,UCM
Alva Zajicek,10000479,UCI
Chester Kemfort,10000529,UCD
Alice Mines,10000579,UCI
Gary Vongunten,10000875,UCM
Adrian Shbi,10001036,UCSD

1 个答案:

答案 0 :(得分:1)

对于计算排序,您首先要计算学校有多少学生(第一次通过数组)。然后你推断每个学校的第一个学生的索引。最后,您将学生存放在目标数组中的正确位置(第二次传递数组)

计数排序不是就地排序,因此您应该将另一个数组传递给该函数以获取已排序的值。

/*
 * Sorts students by school. An implementation of counting sort.
 * @param students array already sorted by ID
 * @param len Array length
 */
void sortByGroupById2(Student students[], Student* sorted[], int len) {
    int count[6];

    // initialization
    for(int i=0; i<6; i++) count[i] = 0;

    // how many students by school
    for (int i=0; i<len; i++) {
        count[schoolToIndex(students[i].getSchool())]++
    }

    // convert number of students per school into index of first student
    int rank = 0, old;
    for (int i=0; i<6; i++) {
        old = count[i];
        count[i] = rank;
        rank += old;
    }

    // affect students in correct places
    for (int i=0; i<len; i++) {
        rank = count[students[i].getSchool()]++; // rank in sorted array will be current
               // value of count for the school (first place for first time) and that
               // value is incremented to be ready for next student for this school
        sorted[rank] = &Student[i];
    }
}

那样sorted计算学生按学生排序的指针。

参考文献:Wikipedia