C 如何使用基于非比较的方法进行分类
C++ how to sort using non comparison based method
- 您通过学生阵列来计算每个学校中有多少学生。您将计数存储在计数数组中。
- 您分配另一个大小等于输入数组的学生数组。您将使用此温度阵列保存排序的元素。
- 使用计数数组,您可以通过注意到学校的起始索引是所有人的累计学生数量来计算每个学校的开始索引在阵列之前的学校。例如:如果计数为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;
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是否有一种有效的方法可以将一系列对象与父/子关系分类
- C 如何使用基于非比较的方法进行分类
- 如何区分类的两个组件共享的常用命名方法