gpt4 book ai didi

c++ - 合并排序问题,在方法之间传递数组?

转载 作者:太空狗 更新时间:2023-10-29 23:07:18 25 4
gpt4 key购买 nike

我正在编写一个实现快速排序、插入排序和归并排序的程序。除了合并排序,我可以得到所有的工作,但我不知道为什么。请忽略操作和比较变量。它们是这样的,所以我可以分析不同输入文件的运行时间和操作次数。此代码以这种方式从 main 通过类对象运行:

Merge testobj13(test_Med[0], 100);
testobj13.merCall();
testobj13.display();

对于排序列表,该类保持列表排序,对于反转列表,除了第一个和最后一个值外,列表几乎仍然保持反转,对于随机列表,我看不到输出和原始输入之间的任何模式。在等待答案时,我将尝试回答其他问题。欢迎任何批评,即使它只是关于我的代码或语法,与这里的整体问题无关。我根据我的算法类编写的 sudo 代码编写了这段代码,所以我很难找出这里的问题。

# include <iostream>
# include <stdio.h>
# include <stdlib.h>

using namespace std;
class Merge{
public:
int comparisons, operations, middle, i, j, k, size;
int *myArray, *c;

Merge::~Merge(){
myArray = 0;
delete myArray;
}

Merge::Merge(int a [], int n) {
size= n;
myArray= new int[size];
comparisons = 0, operations = 0, middle = 0, i = 0, j = 0, k = 0;

for(int x = 0; x < size; x++){
myArray[x] = a[x];
}
}

void combine(int arr [], int first, int middle, int last){

i = first, j = middle + 1, k = first; operations = operations + 3;
c = new int[last + 1]; operations ++;

while( (i <= middle) && (j <= last) ){
comparisons++;operations++;
if(arr[i] <= arr[j]){operations++;
c[k] = arr[i]; operations++;
i++; operations++;
}
else{
c[k] = arr[j]; operations++;
j++; operations++;
}
k++; operations++;
}
while(i <= middle){operations++;
c[k] = arr[i]; operations++;
i++; operations++;
k++; operations++;
}
while(j <= last){operations++;
c[k] = arr[j]; operations++;
j++; operations++;
k++; operations++;
}
for(int k = first; k <= last; k++){operations++;
arr[k] = c[k]; operations++;
}
c = 0;
delete c;
}

void mer(int arr [], int first, int last){
operations++; //for the comparison in the following if statement
if ( first < last ){
middle = (first + last) / 2; operations++;
mer(arr, first, middle); operations++;
mer(arr, middle + 1, last); operations++;
combine(arr, first, middle, last); operations++;
}
}

void merCall(){
mer(myArray, 0, size - 1);
}

void display(){

cout << "The array after going through Merge Sort: " ;

for(int x = 0; x < size; x++){
cout << endl << myArray[x];
}

cout << endl << "Number of operations :" << operations << "\t comparisons: " << comparisons << endl;

}


};

最佳答案

你的“中间”变量在递归期间被覆盖,因为它是类成员而不是局部变量:

middle = (first + last) / 2; operations++;

// This is going to affect middle
mer(arr, first, middle); operations++;

// So this isn't going to work on the range you think it is.
mer(arr, middle + 1, last); operations++;

combine(arr, first, middle, last); operations++;

最好将 middle 声明为局部变量:

int middle = (first + last) / 2; operations++;
mer(arr, first, middle); operations++;
mer(arr, middle + 1, last); operations++;
combine(arr, first, middle, last); operations++;

关于c++ - 合并排序问题,在方法之间传递数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13221246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com