tags:

views:

102

answers:

6

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++){
        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];

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?

+3  A: 

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.

Alexander Rafferty
i have used i and j for the loops and not j for both the for loops
A[j+1] refers to the next element and not add 1 to that element
you can't ask my experience
and this code is sorting an array in increasing order so i am swapping two elements at a time depending upon the if statement and to check every element in a sequential manner i have used that i loop
A: 

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()); 
Default
I think this is cheat as the author seems to learn how to sort himself :)
Benoit
i have just asked what is the problem in my code and whay it is not giving the desired output don't think negative Benoit
it's not cheating unless there are rules stating he is not allowed to use it. :) And it is the easiest way I would think.. Some wheels don't need reinventing
Default
+2  A: 

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

letronje
A: 

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];
JoshD
after changing j with 4 the output is 2 3 4 5 0
Please update your question with the new code. Did you copy and paste my code?
JoshD
A: 

This is exactly the same question as http://stackoverflow.com/questions/3794856/sorting-in-arrays

Benoit
These types of posts are better suited as comments.
Patrick
Ok. was new to stackoverflow, so I am learning too :)
Benoit
A: 

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;
        } 
    }
}
Klark