C 如何使用基于非比较的方法进行分类

C++ how to sort using non comparison based method

本文关键字:方法 分类 比较 何使用 于非      更新时间:2023-10-16

- 您通过学生阵列来计算每个学校中有多少学生。您将计数存储在计数数组中。

- 您分配另一个大小等于输入数组的学生数组。您将使用此温度阵列保存排序的元素。

- 使用计数数组,您可以通过注意到学校的起始索引是所有人的累计学生数量来计算每个学校的开始索引在阵列之前的学校。例如:如果计数为5、10、12,则是学校A,B,C,那么分类阵列中每个学校学生的启动索引为0、5、15

- 您会再次通过学生阵列,每当您遇到一个学生学校您将该学生添加到助手阵列的正确部分,并增加部分的索引。

- 助手阵列现在按学校和ID对每个学校的ID进行排序。复制助手阵列的输入数组的元素。

我在最后两个项目符号上遇到了麻烦。在纸上,我了解算法在做什么,但是实施代码对我来说很难。

我在下面拥有的代码使用计数器来跟踪有多少学生进入7个不同的学校,该学校由计数器阵列的索引代表。然后,它进行了累积计数。我现在需要编码的内容从我的温度数组的右侧开始,并使用累积来对数组进行排序。

 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());
            cout << i << " " << temp[i] << endl;
        }

        // Sets every index in count array to 0
        for(int i =0; i < 7;  i++) {
            count[i]=0;
        }
        //Counts the number of student in 7 different schools
        for(int j =0; j < len;  j++) {
          count[temp[j]]++;
        }
        cout << "====" << endl;
        for(int i =0; i < 7;  i++) {
            cout<< i << " "  <<count[i] <<endl;
        }
          cout << "====" << endl;

        // cumulative counts so we get the starting index for each group
        int total = 0;
        for (int i=0; i<7; i++) {
            int tmp = count[i];
            count[i] = tmp +total;
            total += tmp;
          cout << i << " " << count[i] << endl;
        }
        // Sorts into a new array
        for(int i=0; i <7;i++){
        }
    }

只需按照书面的方式按照以下步骤操作:

// -You allocate another array of Students with size equal to the input array. 
Student* sorted_students = new Student[len];
// – You do another pass through the student array ....
for (int i = 0; i < len; ++i) 
{
    // and whenever you encounter a student from a school ...
    int key = schoolToIndex(students[i].getSchool());
    // you add that student to the right portion of the helper array ...
    sorted_students[count[key]] = students[i];
    //  and increment that portion's index.
    count[key] += 1;
}
// -The helper array is now sorted by school and by ID within each school. 
// Copy the helper array's elements to the input array.
std::copy(sorted_students, sorted_students + len, students);
// and don't forget to delete!
delete [] sorted_students;