-2
有人可以解釋什麼這種排序算法呢?我無法遵循邏輯,它使用遞歸。看起來很奇怪,把中期和第一條(從第8條開始)交換。此外,在第一次迭代中,++last = i
,因此調用swap會浪費。qsort如何工作?
代碼集last = left
,i = left + 1
,然後調用swap()與++last
。這使得last
等於i
!
/* qsort: sort v[left]...v[right] into increasing order */
void qsort(int v[], int left, int right)
{
int i, last;
if (left >= right) /* do nothing if array contains */
return; /* fewer than two elements */
swap(v, left, (left + right)/2); /* move partition elem */
last = left; /* to v[0] */
for (i = left + 1; i <= right; i++) /* partition */
if (v[i] < v[left])
swap(v, ++last, i);
swap(v, left, last); /* restore partition elem */
qsort(v, left, last-1);
qsort(v, last+1, right);
}
/* swap: interchange v[i] and v[j] */
void swap(int v[], int i, int j)
{
int temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
閱讀CLRS算法簡介一書中有關快速排序的章節。 – Sankalp