【发布时间】:2015-04-03 00:05:09
【问题描述】:
例如,我正在编写一个带有条目(字符串键、int 计数)的哈希表。首先,我进行选择排序以按计数对每个条目进行排序。然后我想在保持排序计数的同时按字母顺序对它们进行排序。有没有办法做到这一点?
这是主要排序。
void MyTrends::sortByCount(Entry* arr, int sizeOfArray) {
int maxIndex; // the index of the element that has the highest count
for(int i=0; i < sizeOfArray-1; i++){
maxIndex = i;
for(int j=i+1; j < m; j++){
if(arr[j].getCount() > arr[maxIndex].getCount()){ //if the count of element j is higher than the count of the Entry at the current max index then change the max index to j
maxIndex = j;
}
}
if (maxIndex != i) {
Entry temp = arr[i]; //next 2 lines + this line are swapping max to first position and old first position to the position the max was in
arr[i] = arr[maxIndex];
arr[maxIndex] = temp;
}
}
}
编辑:再想一想,这是否可以通过首先按字母顺序排序,然后使用稳定排序按计数排序来完成?
【问题讨论】:
-
你是对的,如果你首先对辅助键进行排序,然后在稳定的排序算法中使用主排序键,它应该会给你想要的结果:)
-
你的意思是当我们有两个字母顺序相同的元素时,计数最少的那个应该更小?
-
与你刚才所说的相反。如果您有两个计数相同的键,我希望首先显示按字母顺序排列的第一个键。
-
@Slizzered 他是对的,但这仍然不是这样做的方法。这一切都可以在一个排序中完成。
-
啊,下面的最佳答案是一种更好的方法。谢谢大家!