0

在这里,我有这段代码可以按降序对诸如数组之类的锦标赛结构进行排序。它对除一个数字以外的所有数字进行排序,并始终返回-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 进行排序,它会将它们排序为20 8 1 3 -1

4

1 回答 1

0

在 mini maxi 函数中,将 < 和 > 替换为 <= 和 >=

于 2021-10-11T09:18:45.047 回答