Click here to Skip to main content
15,914,111 members
Please Sign up or sign in to vote.
2.33/5 (3 votes)
See more:
I am trying to sort an array in ascending form and this is what i tried. I cant figure out where i made the mistake but the output that i get is complete garbage. Could anyone explain me where my error could be? I am really stuck.

The output that i get is only "4,3,4". Doesnt make any sense!


C++
#include<iostream>
using namespace std;

int main ()
{
int n[6]={5,4,5,3,5,10 };
int counter;

	
	for(int i=0; i<5; i++)
	{
		

		for(int j = i+1; j<6; j++)
		{
			if(n[i+1]<n[i])
			{
				int temp = n[i];
				n[i] = n[i+1];
				n[i+1]= temp;
			
             cout<<n[i];
				

			}
			
			
		}

	}
	
	system("pause");
	
}
Posted
Updated 28-Dec-14 12:28pm
v3

1 solution

The cout is in the wrong place.
The cout will happen only when the if condition is true.

To print the contents of the sorted array you will need a separate loop after all the sorting is done.
So create a new loop after all the sorting is done and cout from that loop.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900