在这里,我有这样的代码,它按降序排列一个类似数组的竞赛结构。它对除一个数字之外的所有数字进行排序,并且总是返回一个-1作为它排序的最低整数,我已经多次阅读了这段代码,我似乎不知道它为什么没有正确排序,我不确定它是缺少了我的眼睛,还是在某个地方有一个小的错误。
#include <iostream>
#include <cmath>
using namespace std;
int maxi(int i, int j)
{
if (i > j) return(i);
else return(j);
}
int mini(int i, int j)
{
if (i < j) return(i);
else return (j);
}
int buildtourn(int tourn[], int n)
{
int min1=0, a;
//Compute tournament structure
for (int i=2*n-2; i>1; i=i-2)
{
tourn[i/2] = maxi(tourn[i], tourn[i+1]);
a=mini(tourn[i], tourn[i+1]);
if (min1>a) min1=a;
}
return min1;
}
int getnext(int tourn[], int n, int low)
{
int i = 2;
//Part 1 - downward traversal
while (i <= 2*n-1)
{
if (tourn[i]>tourn[i+1])
{
tourn[i]=low;
i=2*i;
}
else
{
tourn[i+1]=low;
i=2*(i+1);
}
}
//Part 2 - upward traversal
for (i = i/2; i>1; i=i/2)
{
if (i%2==0) tourn[i/2]=maxi(tourn[i],tourn[i+1]); // go to the right of i
else tourn[i/2]=maxi(tourn[i], tourn[i-1]); // to the left of i
}
return 0;
}
int main()
{
int tourn[100], n, i, low;
//Read
cout << "Give n :" ;
cin >> n;
cout<< "Enter the integers to be sorted : " << endl;
for (i=n; i<=2*n-1; i++)
cin >> tourn[i];
//build tournament
low=buildtourn(tourn,n)-1;
//Sorting
cout << " Sorted items are : " << endl;
for(i=1; i<=n; i++)
{
cout << tourn[i] << '\t';
getnext(tourn,n,low);
}
cout << '\n';
return 0;
}我相信错误完全在于我的函数,它构建了锦标赛的结构,但是,我不太确定我是不是找错了地方。
int buildtourn(int tourn[], int n)
{
int min1=0, a;
//Compute tournament structure
for (int i=2*n-2; i>1; i=i-2)
{
tourn[i/2] = maxi(tourn[i], tourn[i+1]);
a=mini(tourn[i], tourn[i+1]);
if (min1>a) min1=a;
}
return min1;
}谢谢您的帮助,如果我需要在这个问题上添加更多的细节,请在评论中告诉我。
编辑:这是一个链接,以查看我正在接收的输出。http://imgur.com/a/KNDO8
编辑2:如果我使用要排序的数字20 14 1 3 8,它会将它们排序为2 0 8 1 3 -1。
发布于 2021-10-11 09:18:45
在小型maxi函数中,用<=和>=代替< and >
https://stackoverflow.com/questions/39946443
复制相似问题