解决未校正的序列(4,3,2,1,5),并根据我的建议将其更改为校正序列

时间:2018-06-17 22:42:20

标签: c++ arrays sorting sequence

我尝试解决这个问题,并建议我安排Ascending安排从小数字升序到高位序列。

所以我用c ++制作这段代码: -

include<iostream.h>
int main()
  {
   int ar[5] = {4,3,2,1,5};
      int d;
        for (int i=0; i<=4; i++)
        cout<<ar[i]<<" ";
        cout<<endl;
       for (int x=0; x<=4; x++)
            {
          for(int y=x+1; y<=4; y++)
             if(ar[x] > ar[y])
           {
              d=ar[x];
           ar[x]=ar[y];
          ar[y]=d;

           for ( d=0; d<=4; d++)
            {
         cout<<ar[d]<<" ";
                 }
             return 0;
           }
         }
        }

我得到了这个输出

 Output
   4 3 2 1 5
   3 4 2 1 5 

这是我第一次使用cplus 所以我的条件有什么不对

此致

1 个答案:

答案 0 :(得分:0)

算法是正确的。你用括号搞砸了一下。

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
    int ar[5] = {4,3,2,1,5};
    int d;
    for (int i=0; i<=4; i++)
        cout<<ar[i]<<" ";
    cout<<endl;
    for (int x=0; x<=4; x++)
    {
        for(int y=x+1; y<=4; y++)
            if(ar[x] > ar[y])
            {
                d=ar[x];
                ar[x]=ar[y];
                ar[y]=d;
            }

    }
    for ( d=0; d<=4; d++)
    {
        cout<<ar[d]<<" ";
    }
    return 0;
}

正确使用制表,以便更容易阅读并发现此类错误。

如果您的任务没有限制,请记住C ++内置算法(例如std::sort