I have a question about the following code for Insertion Sort:
void insertion(Item a[], int ell, int r)
{
int i;
for (i=ell+1; i<=r; i++)
compexch(a[ell], a[i]);
{
for (i=ell+2; i<=r; i++)
{
int j=i;
Item v=a[i];
while(less (v, a[j-1]))
{
a[j]=a[j-1];
j--;
}
a[j]=v;
}
}
}
Ok, so my question is specifically about the while loop portion-I see that j is decremented and want to know what happens when j=0 and the a[-1] occurs. I do not understand how we can allow a negative index-what if the information we compare happens to work out and the while loops continues to run? Thanks.
I assume compexch(x,y)
does something like if (less(y,x)) { Item t = x; x=y; y=t }
if (less(y,x)) { Item t = x; x=y; y=t }
if (less(y,x)) { Item t = x; x=y; y=t }
. So after the first for
loop finishes, then a[ell]
contains the least Item
out of a[ell+1],...,a[r]
. Now j
is initialized with the value i
, which is at least ell+2
, so we have j > ell
on entry to the while
loop. If the while
loop doesn't terminate sooner, we will eventually get down to j == ell
. Since a[ell]
has already been set to the least element in the range, less(v, a[ell])
will necessarily return false, and the loop will terminate then.
So j
will never decrease to a value less than ell
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.