Sorting numbers in ascending order

Jul 24, 2015 at 5:52am
Hello everyone, I'm trying to write a simple program that will get input from the user for 3 numbers and output them in ascending order. I have code that I looked through just to get an example, but there is one part which I do not understand why it is there.

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
#include <iostream>


int main()
{
    int Array[3], i, j, temp;   

    for (i = 0; i < 3; i++){    
        std::cout << "Enter the " << i << " number to sort:\n"; // i is the numbers to be sorted such as 3, 24, 4
        std::cin >> Array[i];   
    }

    // sort the array
    for (i = 0; i < 3; i++){    
        for (j = 0; j < 3; j++) 
        if (Array[i] < Array[j]){   
            temp = Array[i];
            Array[i] = Array[j];    
            Array[j] = temp;        
        }
    }

    for (i = 0; i < 3; i++){    
        std::cout << Array[i] << std::endl; 
    }

    return 0;
}


I do not get this bit here:

1
2
3
4
5
6
7
8
9
// sort the array
    for (i = 0; i < 3; i++){    
        for (j = 0; j < 3; j++) 
        if (Array[i] < Array[j]){   
            temp = Array[i];
            Array[i] = Array[j];    
            Array[j] = temp;        
       }
}


What is this j variable used for and how does incrementing it somehow determine whether it is bigger or smaller than the 3 elements stored in Array[i] and put them in ascending order?

I appreciate any help, thank you :)
Jul 24, 2015 at 6:34am
I think the sorting code is to put the array in a descending order.
About the algorithm part, it's a very simple and straight forward sorting algorithm. It compares every element with other elements, and swap them if they are not in desired order.
Jul 24, 2015 at 6:45am
Ah yes it is. Got that part of the question mixed up, apologise for that.

As for the algorithm, I understand what it does, it's just understanding how it does it if that makes sense.

The way I'm seeing it go in my head is like this:

Is i less than j? No (for 3 loops)
temp = 3, 24, 4(for each loop)
Array[i] = 0 (Array[j])
temp = 0
Topic archived. No new replies allowed.