比较两个QuickSort函数# JobHunting - 待字闺中
K*k
1 楼
都是取第一个元素为支点, 哪个写得更好?
void quickSort1(int arr[], int left, int right)
{
if (left >= right)
return;
int pivot = arr[left];
int i = left;
int j = right + 1;
while (i < j)
{
do { i++; } while (i <= right && arr[i] < pivot);
do { j--; } while (arr[j] > pivot);
if (i < j)
swap(arr, i, j);
}
swap(arr, left, j);
quickSort1(arr, left, j - 1);
quickSort1(arr, j + 1, right);
}
=======================================================================
void quickSort2(int arr[], int left, int right)
{
if (left >= right)
return;
int pivot = arr[left];
int i = left - 1;
int j = right + 1;
while (i < j)
{
do { j--; } while (arr[j] > pivot);
do { i++; } while (arr[i] < pivot);
if (i < j)
swap(arr, i, j);
}
quickSort2(arr, left, j);
quickSort2(arr, j + 1, right);
}
void quickSort1(int arr[], int left, int right)
{
if (left >= right)
return;
int pivot = arr[left];
int i = left;
int j = right + 1;
while (i < j)
{
do { i++; } while (i <= right && arr[i] < pivot);
do { j--; } while (arr[j] > pivot);
if (i < j)
swap(arr, i, j);
}
swap(arr, left, j);
quickSort1(arr, left, j - 1);
quickSort1(arr, j + 1, right);
}
=======================================================================
void quickSort2(int arr[], int left, int right)
{
if (left >= right)
return;
int pivot = arr[left];
int i = left - 1;
int j = right + 1;
while (i < j)
{
do { j--; } while (arr[j] > pivot);
do { i++; } while (arr[i] < pivot);
if (i < j)
swap(arr, i, j);
}
quickSort2(arr, left, j);
quickSort2(arr, j + 1, right);
}