【发布时间】:2015-11-09 21:09:57
【问题描述】:
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;
}
void sortByGroupById2(Student students[], int len) {
int numberofschools = 7;
int counters[numberofschools];
for (int i = 0; i < numberofschools; i++) {
counters[i] = 0;
}
for (int i = 0; i < numberofschools; i++) {
counters[schoolToIndex(students[i].getSchool())]++;
}
Student *sortedArray = new Student[len];
for (int i = 0; i < len; i++) {
sortedArray[counters[schoolToIndex(students[i].getSchool())]] = students[i];
counters[schoolToIndex(students[i].getSchool())]++;
}
for (int i = 0; i < len; i++) {
students[i] = sortedArray[i];
}
}
int main() {
const int LEN = 350000;
// Rough timing
Student* uc2 = readStudentsFromFile("uc_students_sorted_by_id.txt", LEN);
time(&start);
sortByGroupById2(uc2, LEN);
time(&end);
cout << "Using counting sort it took " << difftime(end, start) << " seconds." << endl;
writeStudentsToFile(uc1, LEN, "uc_by_school_by_id1.txt");
writeStudentsToFile(uc2, LEN, "uc_by_school_by_id2.txt");
return 0;
}
我遇到的具体问题在代码中
sortedArray[counters[schoolToIndex(students[i].getSchool())]] = students[i],
我有sortedArray的开始索引是学校的学生人数。我不知道该怎么做是让开始索引是之前学校的累计学生数。
例如,如果我想要 UCLA 的开始索引,我需要将 UCB 和 UCD 和 UCI 的学生数相加才能得到这个桶的开始索引。
所以我的行动计划是让 counters 数组存储学生人数的组合值。 例如,如果我的 counters 数组有 [5, 10, 15, 20] 作为学生人数,我希望它存储 [5, 15, 30, 50] 作为我的 sortedArray 的起始索引数组。
有什么方法可以用来做这个吗?我使用递归吗?
【问题讨论】:
-
你标记这个
bucket-sort有什么原因吗?
标签: c++ sorting bucket-sort counting-sort