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.
#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 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.