快速排序算法
快速排序算法一、快速排序算法详解二、快速排序代码实现(C++)三、学习链接一、快速排序算法详解二、快速排序代码实现(C++)#include<iostream>#include<vector>using namespace std;//分割函数int Partition(vector<int>& A, int low, int high){int piv
·
一、快速排序算法详解
二、快速排序代码实现(C++)
#include<iostream>
#include<vector>
using namespace std;
//分割函数
int Partition(vector<int>& A, int low, int high)
{
int pivot = A[low];
while (low < high)
{
while (low < high && A[high] >= pivot)
{
high--;
}
A[low] = A[high];
while (low < high && A[low] <= pivot)
{
low++;
}
A[high] = A[low];
}
A[low] = pivot;
return low;
}
//快排函数
void QuickSort(vector<int>& A, int low, int high)
{
if (low < high)
{
int pivot = Partition(A, low, high);
QuickSort(A, low, pivot - 1);
QuickSort(A, pivot + 1, high);
}
}
//快速排序2
int Partition1(vector<int>& A, int low, int high)
{
int pivot = A[low];
while (low < high)
{
while (low < high && A[low] >= A[high])high--;
while (low < high && A[low] <= A[high])low++;
swap(A[low], A[high]);
}
swap(A[low], pivot);
return low;
}
void QuickSort1(vector<int>& A, int low, int high)
{
if (low < high)
{
int pivot = Partition(A, low, high);
QuickSort1(A, low, pivot - 1);
QuickSort1(A, pivot + 1, high);
}
}
int main()
{
// 构造一个数组
vector<int> arr;
arr.push_back(2);
arr.push_back(4);
arr.push_back(1);
arr.push_back(0);
arr.push_back(3);
arr.push_back(5);
int N = arr.size();
cout << "输出数组的长度为:" << N << endl;
//排序前输出
cout << "排序前的结果输出:";
for (vector<int>::iterator it = arr.begin(); it != arr.end(); it++)
{
cout << *it << " ";
}
cout << endl;
cout << "排序后的结果输出:";
QuickSort1(arr, 0, N - 1);
cout << "快速排序后:";
for (vector<int>::iterator it = arr.begin(); it != arr.end(); it++)
{
cout << *it << " ";
}
cout << endl;
system("pause");
return 0;
}
三、学习链接
更多推荐
已为社区贡献1条内容
所有评论(0)