1.快速排序的定义
快速排序也是基于“分而治之”思想的排序算法,在排序时首先选定一个主元,使主元左边的都小于主元,主元右边的都大于主元,通过主元再分成两个子数组,在两个子数组上进行递归,最终就排好序了。
2.代码实现
void mySwap(int*a,int*b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int getStandard(int A[], int left, int right)
{
int center = (left + right) / 2;
if(A[left]>A[center])
{
mySwap(&A[left], &A[center]);
}
if(A[left]>A[right])
{
mySwap(&A[left], &A[right]);
}
if(A[center]>A[right])
{
mySwap(&A[center], &A[right]);
}
mySwap(&A[center], &A[right - 1]);
return A[right - 1];
}
void sort(int A[],int left,int right)
{
//取主元
int standard = getStandard(A, left, right);
//遍历排序
int low = left;
int height = right - 1;
while (1)
{
while (A[++low] < standard);
while (A[--height] > standard);
if (low < height)
{
mySwap(&A[low], &A[height]);
}
else
break;
}
mySwap(&A[low], &A[right - 1]);
//实现递归
if (left < low - 1 && low + 1 < right)
{
sort(A, left, low - 1);
sort(A, low + 1, right);
}
}
void Sort(int A[], int N)
{
sort(A, 0, N - 1);
}
int main()
{
int arr[10] = { 9,8,7,6,5,4,3,2,1,0 };
int len = sizeof(arr) / sizeof(arr[10]);
Sort(arr, len);
for (int i = 0; i < 10; i++)
{
printf("%d", arr[i]);
}
return 0;
}
3.时间复杂度
时间复杂度是O(NlogN);