开发者

problem in coding [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Sorting in arrays

int A[5]={1,5,3,2,4};
for(int i=0;i<5;i++){
    for(int j=0;j<5;j++){
        i开发者_StackOverflowf(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];

The desired output must be 1,2,3,4,5 but my output is 0,1,2,3,4. What's the problem in my code?


Firstly, learn to indent properly. It isn't hard. Secondly, it looks like your making a sorting function.

The problem is that you are using the variable j for both for for loops. Don't. Change one to k, or another variable. I assume you are trying to reference the second j with j+1. This just adds 1 to j.

May I ask, do you have any coding experience?

And you should have specified what the problem was with your code, what you expected and what you got.


Looks like you are attempting Bubble sort, why don't you read up on it . I'm sure you can get it working yourself.


You can use Sort instead, works great!

int A[5]={1,5,3,2,4};
vector<int> vec(A, A+5);

sort(vec.begin(), vec.end()); 


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


Your program will not produce that output. It will die at A[j+1] when j == 4. In the last loop you need to write for(int i = 0; i < 5; i++). Secondly, your logic doesn't have much sense. If you want to sort the array this is the code:

for(int i = 0; i < 5; i++){
    for(int j = i + 1; j < 5; j++){
        if(A[j] < A[i])
        {
            int t = A[j];
            A[j] = A[i];
            A[i] = t;
        } 
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜