1.12 快速排序
1.12.1 介绍
**快速排序(QuickSort)**是对冒泡排序的一种改进。其基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据要小,然后在按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,一次达到整个数据变成有序序列。
1.12.2 原理
1.12.3 快速排序实现
注:sort.h 在c语言排序总结—前序准备中
快速排序代码实现
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include "sort.h"
int main() {
//生成LENGTH长度的随机数组,并展示出来
int arr[LENGTH];
createRandomArray(arr);
int count = 0;
for (int i = 0; i < LENGTH; i++) {
printf("%-10d", arr[i]);
count++;
if (count % 10 == 0) {
printf("\n");
}
}
printf("\n");
//统计排序的时间
int begin, end;
begin = clock();
//调用排序
quickSort(arr);
end = clock();
//输出排序结果
for (int i = 0; i < LENGTH; i++) {
printf("%-10d", arr[i]);
count++;
if (count % 10 == 0) {
printf("\n");
}
}
//输出排序时间
printf("排序时间为time=%d\n", end - begin);
system("pause");
}
void quickSort(int arr[]) {
qSort(arr,0,LENGTH);
}
//对数组中的子序列arr[low,high]做快速排序
void qSort(int arr[], int low, int high) {
int pivot;
if (low < high) {
pivot = partition(arr,low,high);//将arr[low,high]一分为二
//算出枢轴值pivot
qSort(arr, low, pivot - 1); //对左边比较小的数组进行递归排序
qSort(arr, pivot + 1, high);
}
}
//交换顺序数组arr中的记录,以便使枢轴记录到位,并返回其所在位置
//此时在枢轴之前的数均小于枢轴处的数,在枢轴之后的数均大于枢轴处的数
int partition(int arr[],int low,int high) {
int pivotKey;
pivotKey = arr[low];
while (low < high) {
while (low < high && arr[high] >= pivotKey) {
high--;
}
swap(arr, low, high);
while (low < high&&arr[low] <= pivotKey) {
low++;
}
swap(arr, low, high);
}
return low;
}
快速排序在10000数据量下的耗时结果为2毫秒:
快速排序在10万数据量下的耗时结果为18毫秒: