# What is the purpose of the swap (v, left, (left + right) / 2) in the qsort () implementation of K & amp; R?

in K&R second edition, section 5.11, page 107:

``````void qsort(void *v[], int left, int right, int (*comp)(void *, void *))
{
int i, last;
void swap(void *v[], int, int);
if (left >= right)
return;
swap(v, left, (left + right)/2);
last = left;
for (i = left+1; i <= right; i++)
if ((*comp)(v[i], v[left]) < 0) /* Here's the function call */
swap(v, ++last, i);
swap(v, left, last);
qsort(v, left, last-1, comp);
qsort(v, last+1, right, comp);
}
```
```

However, I am confused about the "swap(v, left, (left + right)/2);". I think it is useless... What's the purpose of this sentence?

If the sentence is absent, there is no problem if the array V[ ] is random data. However, if V[ ] is sorted data, no swap is encountered, and the variable last is not changed. Thus, last qsort() is equivalent to `qsort(v, left+1, right, comp)`. It means that only one element decreased in recursive call. When comparison number of times in the function is n, comparison needs n + (n-1) + (n-2) + ... + 1 = n(n+1)/2 times to complete. It takes a long time if n is big. Furthermore, if V[ ] is very large, stack overflow error may be encountered. The statement exists to prevent them.
In addition, `(left + right) / 2` should be `left + (right - left) / 2` to prevent overflow error.