两种排序算法在同一个数组上给出了两种不同的输出(quickSort和heapSort)

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

本文关键字:两种 输出 quickSort heapSort 算法 排序 同一个 数组      更新时间:2023-10-16

我不明白为什么当我编译它们时它们会给我不同的输出。例如……当我只编译一个算法时,答案是好的,另一个也是一样的,但是当我同时编译它们时,它们会给我一些奇怪的输出。

我代码:

#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,5,7,12,21,21,44 (heapSort)

我想应该可以了:

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

数组ax在堆栈中紧挨着彼此。看到你如何在输出中有重复的值87,似乎你的排序函数访问你给他们的数组之外的内存。这是缓冲区溢出,一种未定义行为。有了它,你的代码可以做任何事情,因为你有损坏的变量值(或者更糟,损坏的地址/指针)。

仔细检查如何访问数组。记住,长度为8的数组的C数组索引是0..7!