#include<iostream>
#include<vector>
#include<algorithm>
#include "IO.h" //处理输入输出
using namespace std;
//也可将vector<int>nums; 放在全局域
//void quickSort(int i,int j)
//以升序为例 low < 基准 < high
void quickSort(vector<int> &nums,int i,int j) //引用传递,在原数组进行操作
{
int temp; //保存基准元素
int low, high; //遍历low++ high--
low = i; //记录每组起始位置、终止位置
high = j;
if (low > high) //递归出口
{
return;
}
temp = nums[low]; //记录基准元素
while (low != high)
{
//找第一个元素num[high] < temp 的下标
while (temp <= nums[high] && low < high)
{
high--;
}
//找第二个元素num[low] > temp 的下标
while (temp >= nums[low] && low < high)
{
low++;
}
//交换
if (low < high) //low与high没有相遇
{
swap(nums[low], nums[high]);
}
}
//low与high相遇,基准元素与nums[low]交换
nums[i] = nums[low];
nums[low] = temp;
quickSort(nums,i, low - 1); //递归调用
quickSort(nums,high + 1, j);
return;
}
int main()
{
vector<int> nums;
nums = inputNum(); //从键盘输入一组数,保存在nums中
int len = nums.size();
quickSort(nums,0, len-1);
printArray(nums); //输出排序后的数组
system("pause");
return 0;
}
快速排序算法
最新推荐文章于 2025-06-18 16:18:45 发布