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

:(

So what's wrong with it?
- no results
- 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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.