我正在尝试使用插入排序算法对数组进行排序。该数组填充了WordNode
包括word
字段(从文本文件输入)和frequency
字段(用于测量特定单词在文本文件中出现的次数)的元素。我已经实现了排序,以便单词按频率排序(从最低到最高),但如果频率相等,我也想按字母顺序排序。如何同时使用两个不同的标准进行排序?下面是我的排序代码。
public static void sort(ArrayUnorderedList<WordNode> array) {
//create stacks for insertion sort
LinkedStack<WordNode> sorted = new LinkedStack<WordNode>();
LinkedStack<WordNode> temp = new LinkedStack<WordNode>();
//while the array has elements to be sorted
while(!array.isEmpty()) {
//remove current element from array
WordNode currentNode = array.removeFirst();
//while the sorted stack meets sorting criteria
while((!sorted.isEmpty()) && (sorted.peek().getFrequency() < currentNode.getFrequency())) {
//push elements to temp stack
temp.push(sorted.pop());
}
//push current element to sorted stack
sorted.push(currentNode);
//while the temp stack has elements to be replaced
while(!temp.isEmpty()) {
//push elements to sorted stack
sorted.push(temp.pop());
}
}
//replace sorted elements in array
while(!sorted.isEmpty()) {
array.addToRear(sorted.pop());
}
}