第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

我的快速排序?qū)崿F(xiàn)使用了太多比較但無法確定原因

我的快速排序?qū)崿F(xiàn)使用了太多比較但無法確定原因

拉風(fēng)的咖菲貓 2021-12-10 14:49:09
我正在嘗試在 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í)要差得多。
查看完整描述

1 回答

?
蝴蝶不菲

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊

您的索引有幾個(gè)錯(cuò)誤。您的遞歸需要使用您的最終支點(diǎn)位置。


compares += quickSort(arr, left, pivotFinal - 1);

compares += quickSort(arr, pivotFinal + 1, right);

你在不同的地方以不同的方式對(duì)待你的“正確”索引。可能最容易在循環(huán)中使用“<=”


for (int i = left; i < right; i++) // assumes right is after the last index


arr[pivotIndex] = arr[right]; // assumes right IS the last index


查看完整回答
反對(duì) 回復(fù) 2021-12-10
  • 1 回答
  • 0 關(guān)注
  • 119 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)