簡體   English   中英

C ++中的QuickSort無法完成排序

[英]QuickSort in C++ will not finish sorting

有人可以幫我,告訴我為什么快速排序算法不能對最終元素進行排序嗎? 當我輸入時:6 89 2 78 12 19 99 43 7 63我得到了排序的ALMOST:2 6 7 12 78 19 43 99 63 89

我試圖弄清楚自己的意思,但是當我以自己的方式工作時,以為代碼在某個時候會迷失於進行桌面檢查。

#include <iostream>
using namespace std;

// function prototypes
void quickSort(int arrayList[], int left, int right);
int choosePivot(int arrayList[], int listSize);
int partition(int array[], int left, int right);
void printArray(int theArray[], int Size);
// void swap(int value1, int value2);

int main()
{
    int myList[] = {6, 89, 2, 78, 12, 19, 99, 43, 7, 63};
    printArray(myList, 10);
    quickSort(myList, 0, 9);
    printArray(myList, 10);

    //int myList2[] = { 7, 4, 9, 10, -9 };
    //printArray(myList2, 5);
    //quickSort(myList2, 0, 5);
    //printArray(myList2, 5);


    cin;
    getchar;
    getchar;

    return 0;
}


void quickSort(int arrayList[], int left, int right)
{
    //if (left < right)
    if(right > left)
    {
        int p = partition(arrayList, left, right);

        printArray(arrayList, 10);
        quickSort(arrayList, left, p-1);
        quickSort(arrayList, p + 1, right);
    }
}

// left (index value) - left most part of the array we are working on
// right (index value) - right most part of the array we are working on
int partition(int array[], int left, int right)
{
    //int pivot = array[left]; // I will have to write a function to find the
    //  optimum pivot point, this is the naive solution
    int pivot = array[(left+right)/2];


    int i = left;
    int j = right;
    int temp;
    while (i < j)
    {
        //cout << "in the loop" ;
        while (array[i] < pivot)
            i++;
        while (array[j] > pivot)
            j--;
        if (i < j)
        {
            temp = array[i];
            array[i] = array[j];
            array[j] = temp;
            i++;
            j--;
        }
    }

    return i;
}

void printArray(int theArray[], int Size)
{
    for (int i = 0; i < Size; i++)
    {
        cout << theArray[i] << " ";
    }
    cout << endl ;
}

您的partition()函數中存在一個錯誤(我認為這是Hoare分區算法的實現)。 您只需要刪除以下代碼:

        i++;
        j--;

交換值后。

這是更正后的partition()函數代碼:

int partition(int array[], int left, int right)
{
    int pivot = array[(left + right) / 2];
    int i = left;
    int j = right;

    while (i < j) {
        while (array[i] < pivot)
            i++;
        while (array[j] > pivot)
            j--;
        if (i < j) {
            int temp;

            /* Swap array[i] and array[j] */
            temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }

    return i;
}

即使已修復此錯誤,也應為您的quicksort實現創建一個好的單元測試,因為可能還會存在其他一些細微的錯誤(很難從頭開始編寫沒有bug的partition()實現)。 單元測試中檢查邊緣情況,拐角情況和邊界情況

我不確定這有多大幫助,但是當您掌握

(left + right) / 2

您正在執行(0 + 9)/ 2,即4。但是事實是,如果數組的大小為10,則中間應該為5。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM