Sorting in arrays

2019-02-27 17:38发布

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];

4条回答
我欲成王,谁敢阻挡
2楼-- · 2019-02-27 18:19

Is there a reason you are doing bubble sort, other then trying to learn it? It's one of the slower sorts.

查看更多
闹够了就滚
3楼-- · 2019-02-27 18:22

Perhaps you are printing i instead of A[i] in the printing loop, as in

for( int i = 0; i < N; i++ ) {
    cout << i << ",";          // by mistake, printing i instead of A[i]
}
查看更多
SAY GOODBYE
4楼-- · 2019-02-27 18:28

Why not use the STL sort?

#include <algorithm>

std::sort(A, A+5);
查看更多
手持菜刀,她持情操
5楼-- · 2019-02-27 18:39

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];
查看更多
登录 后发表回答