快速排序
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define max 10
int oneQuickSort(int a[],int low,int high)
{
int tmp = a[low];
while(low<high)
{
while(a[high] >= tmp && low<high)
high--;
if(low<high)
a[low++] = a[high];
while(a[low] <= tmp && low<high)
low++;
if(low<high)
a[high--] = a[low];
}
a[low] = tmp;
return low;
}
void QuickSoort(int a[], int low,int high)
{
int mid;
if(low<high)
{
mid = oneQuickSort(a,low,high);
QuickSoort(a,low,mid-1);
QuickSoort(a,mid+1,high);
}
}
void input(int a[])
{
srand(time(NULL));
for(int i=0; i<max; i++)
a[i] = rand()%99+1;
}
void output(int a[])
{
for(int i=0; i<max; i++)
printf("%-3d", a[i]);
printf("\n");
}
int main()
{
int a[max];
input(a);
output(a);
QuickSoort(a,0,max-1);
output(a);
}
时间复杂度 | 空间复杂度 | |
---|---|---|
最好 | O( nlogn ) | O( log₂n ) |
最坏 | O( n² ) | O( n ) |
平均 | O( nlogn ) | O( logn ) |
另:快速排序是不稳定排序。