Hi,
Can anyone help me in this code bubble sort in c++,,,
this is my code.......

``````void main()
{
int A[5]={7,2,10,15,3};
int i,j,swap;
for(j=0;j<5;j++)
{
for(i=0;i<5;i++)
{
if(A[i]>A[i+1])
{
swap=A[i];
A[i]=A[i+1];
A[i+1]=swap;
}
}

}
for(i=0;i<5;i++)
cout<<A[i]<<endl;

}``````

:(

4
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by Lotus_2011

So what's wrong with it?
- all the numbers the same?
- it isn't sorting at all?
- sorts in the wrong order?
- it doesn't compile (hint, void main is wrong to begin with).

Show some analysis of the problem as well, don't just dump the code, say "it doesn't work" and expect people to do the rest of the work (and guess what you really wanted).

is it outputting
2
7
10
3
15
I bet it is, you wonder what might be the problem now huh?

Writing out in words what your doing goes a long way

``````for(j=0;j<5;j++)
{
for(i=0;i<5;i++)
{
if(A[i]>A[i+1])
{
swap=A[i];
A[i]=A[i+1];
A[i+1]=swap;
}
}
}``````

to me this means:

1. start at address 0 of the A interger array
2. if A[0] (which is 7 ) is greater than A[1](2) switch positions--true
3. then next start at A[1] (which is now 7) if A[1] greater than A[2] switch --false so it moves on
4. ----
5. The problem occurs here if A[3] (15) greater than A[4] (3) switch. -- so that leaves you with the output above, the swap function you have is correct but it should not be in that conditional statement. Think harder.

-hi ,sorry for my way in explaning my problem.
-So I knew my default in my code ,
Its the second for loop
it should be for(i=0;i<4;i++),As i compare between A&A[i+1],
-Another thing this is bubble sort

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.