在数组排序 [英] Sorting in arrays

查看:106
本文介绍了在数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然对数组排序
为前:A [5] = {1,4,5,3,2}
输出必须按升序1,2,3,4,5。
用泡沫排序的概念
我的输出为0,1,2,3,4
这将是我的code中的问题。

  int类型的[5] = {1,5,3,2,4};
     的for(int i = 0;我小于5;我++){
     为(中间体J = 0; J&小于5; J ++){
     如果(A [J]>一种[D + 1])
     {
      INT T = A [J]。
      A [D] = A [J + 1];
      A [J + 1] = T;
     }
     }
    }
     对于(I = 0; I&小于5;我+ +)
     COUT<< A [I]


解决方案

您需要限制内环至< 4:

  int类型的[5] = {1,5,3,2,4};
的for(int i = 0;我小于5;我++){
    为(中间体J = 0; J&下; 4; J ++){
        如果(A [J]>一种[D + 1])
        {
           INT T = A [J]。
           A [D] = A [J + 1];
           A [J + 1] = T;
        }
    }
}
对于(I = 0; I&小于5;我+ +)
   COUT<< A [I]

While sorting an array for ex: A[5]={1,4,5,3,2} the output must be 1,2,3,4,5 in ascending order. in using the concept of bubble sorting my output is 0,1,2,3,4 what would be the problem in my code

  int A[5]={1,5,3,2,4};
     for(int i=0;i<5;i++){
     for(int j=0;j<5;j++){
     if(A[j]>A[j+1])
     {
      int t=A[j];
      A[j]=A[j+1];
      A[j+1]=t;
     }
     }
    }
     for(i=0;i<5;i++)
     cout<<A[i];

解决方案

You need to limit your inner loop to <4:

int A[5]={1,5,3,2,4};
for(int i=0;i<5;i++){
    for(int j=0;j<4;j++){
        if(A[j]>A[j+1])
        {
           int t=A[j];
           A[j]=A[j+1];
           A[j+1]=t;
        } 
    }
}
for(i=0;i<5;i++)
   cout<<A[i];

这篇关于在数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆