what's wrong with this bubble sort?

Hi, I wrote this code for a bubble sort, and I think it's correct but doesn't work properly, the output is wrong especially when the input is negative numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream.h>

int main(void)
{
	long temp;
	int i, j;
	long number[10];
	cout<<"Please enter 10 numbers in row to see the sorted ones:" <<endl;
	for(i = 0; i < 10 ; i++)
		cin >> number[i];
	for(i = 0 ; i <9 ; i++)
	{
		for (j = 0 ; j <9 ; j++) // bubble sort
		{
			if(number[j] > number[j+1])
				temp = number[j];
				number[j]= number[j+1];
				number[j+1] = temp;	
		}
	}
	for(j = 0 ; j < 10 ; j++)
		cout << number[j] << "  ";
	return 0 ;
	
}


which part is wrong? I use VC6 thanks in advance
For one, the if statement is only executing line 16, not lines 16-18. Use braces around the contents of the if statement to execute them all.

Second, watch your indices--they go out of bounds.
Last edited on
thanks, I forgot
Topic archived. No new replies allowed.