快速排序是通过对序列不断划分,把原始序列以划分元素为界形成两个子序列,再对子序列重复划分的过程。这是一个递归的过程,终止条件就是最终所有的子序列都只含有一个元素。
首先需要一个数组序列,再对其进行划分(重点就是划分)。每次划分都需要设置前后两个指针(low和high),两个指针依次往中间位置移动,当指针重合时,结束这一次划分,还需要设置一个枢轴(temp)。最后的结果分三块,第一块的元素都小于第二块元素,第三块都大于第二块。所以第一次划分大概如下图:
现在讲一下两个指针是如何将序列划分的:先是从high指针往前走,如果high指针所指向的数比枢轴(temp)大的话则继续往前走,直到碰见比枢轴小的数时将这个high指针所指向的数复值给low指针指向的位置。接着就从low指针开始往后走,当遇见比枢轴(temp)大的数就将low指针所指向的数复值给high现在指向的位置。重复以上操作,直至high和low指针指向同一个位置是停止上面的操作,但是需要将枢轴(temp)的数复值给这个位置上的数。这样就出现了三块序列。
int partition(int arr[], int low, int high)
{
int temp = arr[low];
while (low < high)
{
while (arr[high] >= temp && low < high)
{
high--;
}
if (arr[high] < temp)
{
arr[low] = arr[high];
low++;
}
while (arr[low] <= temp && low < high)
{
low++;
}
if (arr[low] > temp)
{
arr[high] = arr[low];
high--;
}
}
arr[low] = temp;
return low;
}
再接下来就是重复操作,从第一块中再分三块,也需要前后指针以及枢轴。我就不再重复了,就划分好的序列画出来:
第三块也是一样的操作 ,如下图:
void quicksort(int arr[], int low, int high)
{
int k;
if (low < high)
{
k = partition(arr, low, high);
quicksort(arr, low, k - 1);//第一块序列
quicksort(arr, k + 1, high);第三块序列
}
}
一直重复上面操作,直至出现 :
这就是就是快速排序的所有步骤。
现在我把从头到尾的代码发出来:
#include <stdio.h>
#include <stdlib.h>
int partition(int arr[], int low, int high)
{
int temp = arr[low];
while (low < high)
{
while (arr[high] >= temp && low < high)
{
high--;
}
if (arr[high] < temp)
{
arr[low] = arr[high];
low++;
}
while (arr[low] <= temp && low < high)
{
low++;
}
if (arr[low] > temp)
{
arr[high] = arr[low];
high--;
}
}
arr[low] = temp;
return low;
}
void quicksort(int arr[], int low, int high)
{
int k;
if (low < high)
{
k = partition(arr, low, high);
quicksort(arr, low, k - 1);
quicksort(arr, k + 1, high);
}
}
int main()
{
int arr[] = { 52,49,80,36,14,58,61,97,23,75 };//想要一个一个敲进去就用for循环
int low = 0;
int high = 9;
printf("排序后的顺序:\n");
quicksort(arr, low, high);
for (int i = 0; i <= 9; i++)
{
printf("%d ", arr[i]);
}
return 0;
}