by senfiaj · 2w ago · 0 comments
After the first nested loop run A[1] will have the largest value.
After the second nested loop run A[1] will always be swapped with A[2] (unless they are equal, logically doesn't change anything). A[2] now contains the largest value.
After the k-th (k >= 2) nested loop run, if you pay attention, the k-th element will be inserted into the first k-1 sorted elements. When j >= i, it can no longer do anything, since A[k] will contain the largest value.
After the k-th (k >= 2) nested loop run the first k elements will be sorted relative to each other. The first nested loop is special by bringing the largest element to A[1], the consecutive ones are just inserting A[k] into the sorted first k - 1 elements from the beginning of the array.
No comments yet.