两种排序算法在同一个数组上给出了两种不同的输出(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,5,7,12,21,21,44 (heapSort)
我想应该可以了:
heapSort(x,7);
quickSort(a,0,7);
数组a
和x
在堆栈中紧挨着彼此。看到你如何在输出中有重复的值87
,似乎你的排序函数访问你给他们的数组之外的内存。这是缓冲区溢出,一种未定义行为。有了它,你的代码可以做任何事情,因为你有损坏的变量值(或者更糟,损坏的地址/指针)。
仔细检查如何访问数组。记住,长度为8的数组的C数组索引是0..7!
相关文章:
- 在C++中将函数压缩为两种方式
- 如何使映射键具有两种不同的数据类型?
- 两种访问I2C总线的方法有什么区别?
- 两种模板示例有什么区别?
- 如何构造可以调用和返回两种不同类型的模板
- 这两种C++语法之间有什么区别?
- 为什么两种不同的对象初始化方式给出不同的输出
- std::cin 从控制台获取两种不同的变量类型,'storing'以后使用第二种类型?
- 定义类模板构造函数的两种方法之间的区别
- 初始化类的两种方法?
- C++ 一个函数,可以根据接受的值返回两种类型之一
- 如何检查程序员在C++中提供的两种不同格式的输入
- C++指针中的这两种类型的值分配有什么区别?
- 如何在c ++中以一行(水平)打印两个文件的数据?如给定的.这两种形式来自两个不同的文本文件
- 两种情况下的输出不应该相同吗?
- 为什么这两种输出样式给出不同的答案
- 如何根据两种输入状态编写输出结果
- C++中的两种类型的矩阵输出
- 我的c++代码在ideone和codeforces自定义测试中提供了两种不同的输出
- 两种排序算法在同一个数组上给出了两种不同的输出(quickSort和heapSort)