我正在尝试实现一种方法,使用快速排序算法对键的数组列表进行排序(按降序方式)。
这是用于赋值的,因此我们只允许使用java.util.arraylist、java.util.hashmap和java.util.map.entry(尽管我相信其他工具可以更轻松地实现这一点)。
我试图通过对较小的列表使用insertionsort来加速我的快速排序算法,但是这样做时,我得到了错误的排序值。我肯定插入排序有问题,但我不确定是什么。请帮忙!
具体插入排序方法如下:
private static <K extends Comparable<K>> void insertionSort(ArrayList<K> elements, int beg, int end){
for (int i = beg + 1; i <= end; i++){
K currentElement = elements.get(i);
while (i >= beg && elements.get(i).compareTo(currentElement) < 0){
elements.set(i+1, elements.get(i));
i--;
}
elements.set(i+1,currentElement);
}
整个代码(包括快速排序)如下所示:
//public method to return an array list containing all keys, quickly ordered in descending order
public static <K extends Comparable<K>, V> ArrayList<K> fastSort(HashMap<K, V> results)
{
//create a new array list of type K to store the ordered key list in
ArrayList<K> sortedUrls = new ArrayList<K>();
//insert all the keys of the specified hash map to the new list
sortedUrls.addAll(results.keySet());
//call the quicksort method to sort the array list
quicksort(sortedUrls,0, sortedUrls.size()-1);
return sortedUrls;
}
private static <K extends Comparable<K>> void swap(ArrayList<K> elements, int i, int j){
//Method to swap 2 elements in an arraylist
K temp = elements.get(i);
elements.set(i, elements.get(j));
elements.set(j, temp);
}
private static <K extends Comparable<K>> void quicksort(ArrayList<K> elements, int beg, int end){
//make sure that beginning and end indexes are proper
if(beg>=end) return;
if(beg<0) return;
if(end>elements.size()-1) return;
int size = (end+1 - beg);
//incorporating InsertionSort for smaller lists
if (size <= 10){
insertionSort(elements, beg, end);
}
//else use QuickSort for larger lists
else {
//update the pivot and swap appropriate elements using the partition helper method
int pivot = partition(elements, beg, end);
//recursively call quicksort on either side of the pivot
quicksort(elements, beg, pivot - 1);
quicksort(elements, pivot + 1, end);
}
//}
}
private static <K extends Comparable<K>> int partition(ArrayList<K> elements, int beg, int end){
//Get a random pivot between beg and end
int random = beg + (int)Math.random()*(elements.size())/(end-beg+1);
//New position of pivot element
int last=end;
//Move the pivot element to right edge of the array
swap(elements, random, end);
end--;
while(beg<=end){
if(elements.get(beg).compareTo(elements.get(last)) > 0) beg++; //Accumulate smaller elements to the left
else {
swap(elements, beg, end);
end--;
}
}
//Move pivot element to its correct position
swap(elements, beg, last);
return beg;
}
private static <K extends Comparable<K>> void insertionSort(ArrayList<K> elements, int beg, int end){
for (int i = beg + 1; i <= end; i++){
K currentElement = elements.get(i);
while (i >= beg && elements.get(i).compareTo(currentElement) < 0){
elements.set(i+1, elements.get(i));
i--;
}
elements.set(i+1,currentElement);
}
}
暂无答案!
目前还没有任何答案,快来回答吧!