Is there any way to sort five inputed numbers by user in ascending/descending order, not using five differenf for loops and if statements for each number?
I did my coding in my native language, so i am not sure if it would make any sense.
/* a[0] to a[n-1] is the array to sort */
int i,j;
int iMin;
/* advance the position through the entire array */
/* (could do j < n-1 because single element is also min element) */
for (j = 0; j < n-1; j++) {
/* find the min element in the unsorted a[j .. n-1] */
/* assume the min is the first element */
iMin = j;
/* test against elements after j to find the smallest */
for ( i = j+1; i < n; i++) {
/* if this element is less, then it is the new minimum */
if (a[i] < a[iMin]) {
/* found new minimum; remember its index */
iMin = i;
}
}
if(iMin != j) {
swap(a[j], a[iMin]);
}
}
thanks for the answer, i've ended up with my version and I have few questions about it's logic
What does line for (int i = 1; i < pan_array - 1; i++) do? I see that it generates numbers from 1 to 10 in the loop, but i cant see the purpose of it and what value it gets? (is it just how many times will loop run?)
Where does a value of the lowest_num is storred when for loop is ran once?
What does line for (int i = 1; i < pan_array - 1; i++) do?
It makes sure that the inner loop (let's call it a pass, following Wikipedia's conventions) executes
enough times for the array to be sorted. A better approach is to additionally check whether a pass
changes the array and break prematurely if it doesn't (see the Wikipedia implementations).
Where does a value of the lowest_num is storred when for loop is ran once?
I don't understand what you're asking here.
BTW, while it looks conceptually correct, there are unusual conventions
(array indexing starts at 1 instead of 0) as well as off-by-one errors
(e.g. elements[j + 1] when j == pan_array - 1) in your code.