- 你通过学生阵列来计算每所学校有多少学生。您将计数存储在计数数组中。
- 您分配另一个学生数组,其大小等于输入数组。您将使用此临时数组来保存已排序的元素。
- 使用计数数组,您可以通过注意到学校的起始索引是所有学生的累计学生数来计算排序数组中每个学校的起始索引。 阵中的学校。例如:如果学校a,b,c的计数是5,10,12,那么 每个学校的学生在排序数组中的起始索引是0,5,15
- 当你遇到一个学生时,你会再次通过学生数组 学校你将该学生添加到辅助数组的右侧部分并递增 部分的索引。
- 辅助数组现在按学校和每所学校的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++){
}
}
答案 0 :(得分:0)
完全按照以下步骤操作:
// -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;