Arrays exercise: order the elements inside an array in increasing order. Not so easy.
- a01337106
- 10 feb 2015
- 1 Min. de lectura
Now here is a more complex exercise:
Let’s say we have an array A[] of size N=9
This is our array:
A
[0] [1] [2] [3] [4] [5] [6] [7] [8]
7 9 8 6 2 5 1 3 4
We want to put this array in order, but how can we do this?
This is the complete code:
Loop I from 0 to N-1
Loop J from 0 to N-1
If (A[I+1]<A[I]){
X=A[I];
A[I]=A[I+1];
A[I+1]=X;
}
end loop
end loop
Now, the explanation:
For this code two loops are needed, one for comparing each value inside the array and the other to compare all the values N-1 times. Why?
Well we don’t know how far are the numbers from their desired position, for this it is needed to compare each position with the next one so we can now is the next number is a bigger or smaller number. To assure that all the numbers are going to end up in their correct position, we will need to repeat all this comparisons N-1 times.
Inside the two loops we make the comparison between A[I+1] that is the next position and A[I] that is the actual position. If the next element is smaller than the actual element, the elements will swap positions.
This is all repeated until the values inside A[] get to their final positions.
An excellent example is the video on the top. All the comparisons are repeated until every dancer is on their position. Watch the video for a further understanding.
Well, now this is a more complex exercise with arrays.
Comments