利用分治思想:
1、从数组中取出一个数,称为基数(pivot)
2、遍历数组,将比基数大的数字放在其右,比基数小的放在其左。遍历完成后,数组将被分为左右2个区域。
2、将左右两个区域视为2个数组,重复之前步骤,直到排序完成。
在实现过程中,可以借助双指针:
#include <stdio.h>
void quickSort(int* nums, int start, int end) {
if (start > end) {
return;
}
int left = start;
int right = end;
// 快速排序 Step1: 取出一个数,作为基数pivot
int pivot = nums[start]; // 这里取第一个数为基数
// 快速排序 Step2: 遍历数组,将比基数大的数放在其右,比基数小的放在其左
while (start < end) {
while (start < end && nums[end] >= pivot) {
end--; // 对数组倒序遍历
}
// 因为此时end位置的数比基数要小,因此需要将小的数放在其左(star位置,可能并不是数组的最左)。
nums[start] = nums[end]; // 不用担心原来的start处的数,原来的数被暂存在pivot中了
while (start < end && nums[start] <= pivot) {
start++; // 对数组顺序遍历
}
// 因为start位的元素比基数要大,因此需要将这个大的数放在其右(end位置,并不是数组的最右)。
nums[end] = nums[start]; // 不用担心原来的end处的数,原来的数被存在开头了,相当于挪动了
}
nums[start] = pivot;
// 此時start和end都移动到中间了,以此为分隔点,继续对左右数组进行快速排序
quickSort(nums,left,start-1);
quickSort(nums,start+1,right);
}
int main() {
printf("快速排序算法(Quick Sort Algorithm)\n");
int nums[] = {81, 94, 11, 96, 12, 35, 17, 95, 28, 58, 41, 75, 15};
printf("排序前:");
for (int i = 0; i < 13; ++i) {
printf("%d ",nums[i]);
}
quickSort(nums, 0, 12); // 要求传入start和end指针
printf("\n排序后:");
for (int i = 0; i < 13; ++i) {
printf("%d ",nums[i]);
}
return 0;
}
运行结果: