我正在嘗試在 Java 中實(shí)現(xiàn)快速排序,并且正在努力以有效的方式實(shí)現(xiàn)它。我相信問題出在我的遞歸調(diào)用上,但我無法確定如何解決它。我正在使用比較來查看進(jìn)行了多少次比較,以期確定問題出在哪里。我唯一能想到的是在我的遞歸語句周圍需要一個(gè)條件,因?yàn)闊o論輸入的數(shù)組是否已經(jīng)排序或看似隨機(jī),所需的比較量都是相同的。public int quickSort(int[] arr, int left, int right) { //left is lowest index //right is highest index int compares = 0; //calls insertion sort once subsets get smaller than 7 elements if (right - left < 6) { compares += insertSort(arr, left, right); return compares; } //calculate random pivot int pivotIndex = randomInt(left, right); int pivotValue = arr[pivotIndex]; //moves pivot value to rightmost index int temp; temp = arr[pivotIndex]; arr[pivotIndex] = arr[right]; arr[right] = temp; int pivotFinal = left; //determines how many values are lower than the pivot, swapping //smaller values with larger values along the way for (int i = left; i < right; i++) { compares++; if (arr[i] <= pivotValue) { temp = arr[i]; arr[i] = arr[pivotFinal]; arr[pivotFinal] = temp; pivotFinal++; } } //moves pivot to final position so that quicksort is complete temp = arr[pivotFinal]; arr[pivotFinal] = arr[right]; arr[right] = temp; compares += quickSort(arr, left, pivotIndex - 1); compares += quickSort(arr, pivotIndex + 1, right); return compares;}public void main() { QuickSort qs = new QuickSort(); int n = 60; int[] array = qs.GenerateRandomSequence(n); int compares = qs.quickSort(array);}當(dāng) n 為 60 時(shí),其中一個(gè)序列需要超過 400 萬次比較,這比實(shí)際的最壞情況運(yùn)行時(shí)要差得多。
我的快速排序?qū)崿F(xiàn)使用了太多比較但無法確定原因
拉風(fēng)的咖菲貓
2021-12-10 14:49:09