簡體   English   中英

兩種排序算法在同一數組上為我提供了兩個不同的輸出(quickSort和heapSort)!

[英]Two sorting algorithms give me two different outputs on the same array (quickSort and heapSort)!

我不明白為什么當我編譯它們時它們給我不同的輸出。 例如...當我只編譯一種算法時,答案是好的,而對於另一種算法,答案是好的,但是當我同時編譯它們時,它們給了我一些奇怪的輸出。

我的代碼:

#include <iostream>
using namespace std;


int parent(int i){
    return i/2;
}
int leftChild(int i){
    return 2*i+1;
}
int rightChild(int i){
    return 2*i+2;
}
void maxHeapify(int a[], int i, int n){
    int largest;
    int temp;
    int l = leftChild(i);
    int r = rightChild(i);
    //   p.countOperation("CMPbottomUp",n);
    if (l <= n && (a[l] > a[i]))
        largest = l;
    else
        largest = i;
    //      p.countOperation("CMPbottomUp",n);
    if (r <= n && (a[r] > a[largest]))
        largest = r;
    if (largest != i){
        //    p.countOperation("ATTbottomUp",n);
        temp = a[i];
        //  p.countOperation("ATTbottomUp",n);
        a[i] = a[largest];
        //p.countOperation("ATTbottomUp",n);
        a[largest] = temp;
        maxHeapify(a, largest, n);
    }
}

void buildMaxHeap(int a[], int n){
    for (int i=n/2; i>=0; i--){
        maxHeapify(a, i, n);
    }
}
void heapSort(int a[],int n){
    buildMaxHeap(a,n);
    int n1=n;
    int temp;
    for(int i=n1;i>0;i--){
        temp = a[0];
        a[0] = a[i];
        a[i] = temp;
        n1--;
        maxHeapify(a,0,n1);
    }

}

int partitionArray(int arr[], int left, int right){
    int i = left, j = right;
    int tmp;
    int pivot = arr[(left + right) / 2];
    while (i <= j) {
        while (arr[i] < pivot)
            i++;
        while (arr[j] > pivot)
            j--;
        if (i <= j) {
            tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
            i++;
            j--;
        }
    }
    return i;
}

void quickSort(int arr[], int left, int right) {
    int index;
    index = partitionArray(arr, left, right);
    if (left < index - 1)
        quickSort(arr, left, index - 1);
    if (index < right)
        quickSort(arr, index, right);
}

int main(){
    int x[8]= {5,87,21,4,12,7,44,3};
    int a[8];
    for(int i=0;i<8;i++){
        a[i] = x[i];
    }
    heapSort(x,8);
    quickSort(a,0,8);

    for(int i=0;i<8;i++){
        cout<<a[i]<<' ';
    }
    cout<<endl;

    for(int j=0;j<8;j++){
        cout<<x[j]<<' ';
    }

    return 0;
}

輸出示例:

1)當我只編譯一種算法時,輸出為:3,4,5,7,12,21,44,87(很好)

2)當我在代碼中編譯它們兩者時,輸出為:87,4,5,7,12,21,44,87(quickSort)和3,3,4,5,7,12,21,44( heapSort)

數組ax在堆棧中彼此緊鄰。 看到輸出中的重復值87如何,似乎您的排序函數在您提供給它們的數組之外訪問內存。 這是緩沖區溢出,一種未定義的行為。 這樣,您的代碼就可以執行任何操作,因為您破壞了變量值(或更糟糕的是,破壞了地址/指針)。

仔細檢查您如何訪問陣列。 請記住,長度為8的數組的C數組索引為0..7!

我認為這應該工作:

heapSort(x,7);
quickSort(a,0,7);

暫無
暫無

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

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