goldwinbryanr wrote: |
---|
what do you mean by comparing pair of positions in the array |
The line
if(n[i] > n[t]){
compares the i
th element of the array (
n[i]
) with the t
th element (
n[t]
). (Note that C++ and related languages count from 0, not 1, for good, but not easily explained, reasons).
If this statement is true ... then these particular elements are in the wrong order ... and the next block of lines (surrounded by curly braces and indicated by the indentation) will carry out the code to swap them.
Always looks brighter in the morning. (Apart from my bank balance.)
For your particular example (5,1,8,613,23) ...
outer loop i=0 (i.e. compare 0
th element (the start!) with later ones):
t=1: 5 and 1 are wrong way round, so swap to
1,5,8,613,23
t=2: 1 and 8 are ok
t=3: 1 and 613 are ok
t=4: 1 and 23 are ok
At the end of the i=0 loop, the 0th element is correct (1) and will be ignored henceforth. Currently 1,5,8,613,23
Next outer loop i=1
t=2: 5 and 8 are ok
t=3: 5 and 613 are ok
t=4: 5 and 23 are ok
Currently 1,5 are finalised and current status is 1,5,8,613,23
Next outer loop i=2
t=3 then 4: the element 8 is correctly positioned with respect to both of these, so no changes
Currently 1,5,8 are finalised and current status is 1,5,8,613,23
Final outer loop i=3
t=4: 613 and 23 are the wrong way round, so swap
Finishes with 1,5,8,
23,613