# Sort an Array in Ascending Order ?

• 01-09-2008
Coding
Sort an Array in Ascending Order ?
I am trying to figure out how to sort an Array in Ascending order.

The Array I want to sort is:

array[4] // values: 1,3,2,4

I have a example code but are not really sure. I do understand the code almost but I wonder where the stored array are.
Is the sorted array simply: array ?
Does this code make this array in ascending order ?

Code:

```void exchange_sort(apvector <int> &array) {     int i, j;     int temp;  // holding variable     int arrayLength = array.length( );     for (i=0; i< (arrayLength -1); i++)    // to represent element to be compared     {           for(j = (i+1); j < arrayLength; j++)  // to represent the rest of the elements         {                 if (array[i] < array[j])               {                         temp= array[i];          // swap                         array[i] = array[j];                         array[j] = temp;               }           }     }     return; }```
• 01-09-2008
robwhit
array is a reference. It is both the input array and the sorted array.
• 01-09-2008
Coding
I understand.. so If I take the array out after running this code, the array will then be sorted, just to be sure this code works or if it is missing something...

I think this code is for descending order. If you want to do it for ascending order, do you begin the counting from the top rather as for this example from the beginning of the array ?
• 01-09-2008
robwhit
usage would be like this:
Code:

```apvector <int> myarray; //fill myarray exchange_sort(myarray); //my array is now sorted```
Quote:

I think this code is for descending order. If you want to do it for ascending order, do you begin the counting from the top rather as for this example from the beginning of the array ?
The <s>easiest</s> generic, usual way would be to use a reverse iterator.

But I think to change the function, you would have to do this:
Code:

`if (array[i] > array[j])`
disclaimer: untested.
• 01-09-2008
Coding
okay.. thank you... I will try it out and see what I get...
• 01-09-2008
cpjust
or without reinventing the wheel, you'd do this:
Code:

```#include <algorithm> #include <vector> int main() {     std::vector<int> nums;     ...     std::sort( nums.begin(), nums.end() );     ... }```