描述
Code
void quickSort(int r[], int low, int high)
{
int i, j, temp;
i = low;
j = high;
if (i >= j)return;
int x = r[i];
while (i < j) {
while ((i<j) && r[j]>x)--j;
if (i < j) {
r[i] = r[j];
++i;
}
while ((i < j) && r[i] < x)++i;
if (i < j) {
r[j] = r[i];
--j;
}
r[i] = x;
}
quickSort(r, low, j - 1);
quickSort(r, j + 1, high);
}
优化
-
三者取中法确定枢纽
避免对已排序序列造成的浪费i = low; j = high; temp = r[j]; r[j] = r[(i+ j) / 2]; r[(i+ j) / 2] = temp; x=r[j];
void quickSort(int r[], int low, int high)
{
int i, j, temp;
i = low;
j = high;
if (i >= j)return;
temp = r[j];
r[j] = r[(i + j) / 2];
r[(i + j) / 2] = temp;
int x = r[high];
--j;
while (i < j) {
while (r[i] < x)++i;
while (r[j] > x&& j > low)--j;
if (i < j) {
temp = r[i];
r[i] = r[j];
r[j] = temp;
++i;
--j;
}
}
if (i < high) {
temp = r[i];
r[i] = r[high];
r[high] = temp;
}
quickSort(r, low, i - 1);
quickSort(r, i + 1, high);
}