1.每次以数组第一个元素为基数
#include <cstdio>
#include <cstdlib>
void swap(int &a,int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
int* partition(int A[], int L, int R)
{
int less = L - 1;
int more = R + 1;
int cur = L;
int num = A[L];
while (cur < more)
{
if (num>A[cur])
{
swap(A[less + 1], A[cur]);
less++; cur++;
}
else if (num < A[cur])
{
swap(A[cur], A[more - 1]);
more--;
}
else
{
cur++;
}
}
return new int[] {less+1,more-1};//返回两个边界
}
void QuickSort(int A[], int L, int R)
{
if (L < R)
{
int *p=(int*)malloc(sizeof(int)*2);
p = partition(A, L, R);
QuickSort(A, L, p[0]-1);
QuickSort(A, p[1]+1, R);
}
}
int main()
{
int A[] = { 4, 3, 9, 2, 0, 4, 1, 6, 8, 1, 1, 1, 7 };
for (int i = 0; i < 13; i++)
{
printf("%d ", A[i]);
}
printf("\n");
QuickSort(A, 0, 12);
for (int i = 0; i < 13; i++)
{
printf("%d ", A[i]);
}
printf("\n");
system("pause");
return 0;
}
运行结果:
每次以数组最后一个元素为基数
#include <cstdio>
#include <cstdlib>
void swap(int arr[], int i, int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
int *partition(int arr[], int l, int r) {
int less = l - 1;
int more = r;//用最后一个作比较
while (l < more) {
if (arr[l] < arr[r]) {
swap(arr, ++less, l++);
}
else if (arr[l] > arr[r]) {
swap(arr, --more, l);//每次交换后arr位置的数还未比较因此不进行arr++
}
else {
l++;
}
}
swap(arr, more, r);
return new int[] { less + 1, more };//返回两个边界
}
void quickSort(int arr[], int l, int r) {
if (l < r) {
int *p = (int*)malloc(sizeof(int)* 2);
p = partition(arr, l, r);
quickSort(arr, l, p[0] - 1);
quickSort(arr, p[1] + 1, r);
}
}
两种快速排序都减少了相等数的比较次数