# Thread: organize values of array in ascending order

1. ## organize values of array in ascending order

Code:
#include <iostream>
using namespace std;

int main ()

{

cout<<"Type in values\n";
int array[10];

for (int x=0; x<10; x++)

{
cin>>array[x];

}

//the problem seems to be here.

for (int y=0; y<10; y++)

{
if (array[y+1]<array[y])
{
int temp;
temp=array[y+1];
array[y+1]=array[y];
array[y]=temp;

}

}

for (int print=0; print<10; print++)
{

cout<<array[print];
cout<<endl;

}

return 0;

}

2. You'll have to be more specific. Are you getting compiler errors, runtime errors, or just unexpected output?

Note: don't write questions as comments in your code. Place any questions outside the code fragments.

3. it doesn't organize the values like I expected.......

4. I can see why. All you're doing is possibly swapping one element with its neighbour 10 times. This is only part of the sorting process. I don't know sorting however, so I can't really help you. Try googling 'c++ sort algorithm'.

5. Here is your code modified so that it sorts correctly. I don't know if this is the best way to sort, but it is the way that i know and it works fine. it works like this
y is initally set to 0, z to 9. it compares the values and switches them if z<y. then z is set to 8 (y still at 0) numbers are compared and switched if necessary. etc... then it sets y to 1 and compares that with z = 9 through 2. Then y=2 and the program compares that with 9 through 3. etc... It continues comparing until y=8 and z=9. Hope this makes sense. good luck!

Code:
#include <iostream>
using namespace std;

int main ()

{

cout<<"Type in values\n";
int array[10]; //creates array with 9 elements numbers 0 through 9

for (int x=0; x<10; x++)

{
cin>>array[x];  //enters values for array

}

//sorts array
for (int y=0; y<9; y++) //set y to numbers 0 through 8 (one less than greatest value in the array)
{
for (int z=9; z>y; z--) // set z to the top element in the array and deincriment it
{

if (array[z]<array[y])  //Switches the elements if z is less than y
{
int temp;
temp=array[z];
array[z]=array[y];
array[y]=temp;

}

}
}

cout << "------------------------------------------\n"; //makes it easier to read

//displays numbers
for (int print=0; print<10; print++)
{

cout<<array[print];
cout<<endl;

}

system("PAUSE");
return 0;

}