### Code Help

 ``1234567891011121314`` `````` for(i = 0; i <= 5; ++i) { for(j = i + 1; j <= 6; j++) { int temp; if(numb[i] > numb[j]) { temp = numb[i]; numb[i] = numb[j]; numb[j] = temp; } } }``````

It's from this video. However I know what the rest of the code does but this part confuses as me as when I launch the program I still can't see what it does. A visual representation of it would be cool :).
its a standard sorting algorithm. it sorts the elements in the numb[] array in ascending order. it is assumed that the array has 7 elements at addresses 0 to 6.
 ``12345678910111213`` ``````for(i = 0; i <= 5; ++i) // loop through the 1st six elements { for(j = i + 1; j <= 6; j++) // for each ith element loop through the all the elements after it. { // after this loop, smallest element after ith position will be placed at the ith position. int temp; if(numb[i] > numb[j]) // swap if ith element is > jth element { temp = numb[i]; numb[i] = numb[j]; numb[j] = temp; } } }``````

say initial list numb = [6,5,4,3,2,1,0]
after i=0 loop iteration: numb = [0,6,5,4,3,2,1]
after i=1 iteration: numb = [0,1,6,5,4,3,2]
after i=2 iteration: numb = [0,1,2,6,5,4,3]
after i=3 iteration: numb = [0,1,2,3,6,5,4]
after i=4 iteration: numb = [0,1,2,3,4,6,5]
after i=5 iteration: numb = [0,1,2,3,4,5,6]

hope it clarifies..
Last edited on
Thanks, that helped a lot. One more question, why is the for loop for j <=6 instead of <=5?
j<=6 because there are 7 elements and j has to loop till the last element.
i<=5 because i does not have to loop till the last element .j starts from i+1 and does that.
There are 7 elements in the array, therefore the index of the last one is 6.
j starts at i+1, which means i+1 must always be a valid index, which means i+1 <= 6, which means i <= 5.
Topic archived. No new replies allowed.