#include<stdio.h>
int arr[10] = {47, 5, 86, 21, 35, 56, 59, 13, 14, 44};
int low = 0, high = 9;
int pivot;//枢轴
int partition(int low, int high);
void QuickSort(int low, int high);
int main() {
QuickSort(low, high);
/*************输出结果*****************/
for (int i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
return 0;
}
void QuickSort(int low, int high) {
if (low < high) {
int pivotPos = partition(low, high);
QuickSort(low, pivotPos - 1);
QuickSort(pivotPos + 1, high);
}
}
/*
将传入的数组片段进行分隔,把大于pivot的数放在右边,小于pivot的数放在左边
*/
int partition(int low, int high) {
pivot = arr[low];//把传入的数组片段的第一个数作为枢轴
while (low < high) {
//先从右侧开始
while (low < high && arr[high] >= pivot) {
--high;
}
arr[low] = arr[high];
while (low < high && arr[low] <= pivot) {
++low;
}
arr[high] = arr[low];
}
arr[low] = pivot;//最后把枢轴放在中间位置,即low的位置
return low;
}
数据结构--快速排序
最新推荐文章于 2024-11-15 20:48:32 发布