code is sorting descending instead of ascending

Hi, I need help on finding an error in one of my homework problems. I was supposed to create a code using only while loops to create a C++ program to sort a group of numbers so that they are increasing in value. In my code so far, they decrease and I can't seem to figure out why. If someone could point out my error that would help me out a lot. Thanks
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
26
27
28
29
30
31
32
33
34
35
36
37
38
{
	int array[100],n,i,j,temp;
	
	cout<<"How many numbers will be entered: ";
	cin>>n;.
	cout<<"Enter "<<n<<" numbers (Positive, Negative, or 0)\n";
	i=0;
	while (i<n)
	{
		cin>>array[i];
		i++;
	}
	i=0;
	while (i<n)
	{
		i++;
		j=0;
		while(j<n-1)
		{
			if(array[j]>array[j+1])
			j++;
			{
				temp=array[j];
				array[j]=array[j+1];
				array[j+1]=temp;
			}
		}
	}
	cout<<"\nNumbers are sorted in ascending order:\n";
	i=0;
	while (i<n)
	{
		cout<<array[i]<<"   ";
		i++;
	}
	
	return 0;
}
closed account (D80DSL3A)
Line 21 is in the wrong place. Try placing the j++ after the if block so the inner while loop is like this:
1
2
3
4
5
6
7
8
9
10
11
while(j<n-1)
{
	if(array[j]>array[j+1])
        // old location of j++		
	{
		temp=array[j];
		array[j]=array[j+1];
		array[j+1]=temp;				
	}
	j++;// new location
}


I tested this and it seems to work. Good luck!
Last edited on
Thanks! that cleared up one of the issues that I was having with it not returning the right number, but for me it is still in decreasing order not increasing.
closed account (1yR4jE8b)
If your sort is in decreasing order instead of increasing it's because your comparison is backwards. Here's some pseudo-code

descending
1
2
if e1 < e2
     swap(e1, e2)


ascending
1
2
if e1 > e2
     swap(e1, e2)
Topic archived. No new replies allowed.