快排
快速排序
初步了解一下快排的思路:快速寻找一个标准,将数组二分化,然后再以同样的思路直到数组有序。
具体的思路是:快速排序法(详解)
根据此思路,我自己模拟的过程为:
这个解析中提供的代码:
void Quick_Sort(int *arr, int begin, int end){
if(begin > end)
return;
int tmp = arr[begin];
int i = begin;
int j = end;
while(i != j){
while(arr[j] >= tmp && j > i)
j--;
while(arr[i] <= tmp && j > i)
i++;
if(j > i){
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
arr[begin] = arr[i];
arr[i] = tmp;
Quick_Sort(arr, begin, i-1);
Quick_Sort(arr, i+1, end);
}
c++代码如下:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class soultion
{
public:
soultion();
~soultion();
int count = 0;
void quickSort(vector<int> &num, int begin, int end);
};
soultion::soultion()
{
}
soultion::~soultion()
{
}
void soultion::quickSort(vector<int> &num, int begin, int end)
{
if (begin >= end) return;
int i = begin;
int j = end;
// int tmp = num[begin];
while (i < j)
{
while (num[begin] <= num[j] && i < j) j--;
while (num[begin] >= num[i] && i < j) i++;
swap(num[i], num[j]);
}
//bool flag = (i == j ? true : false);
/*if (!count++) {
cout << (i == j ? true : false) << endl;
}*/
swap(num[begin], num[i]);
quickSort(num, begin, i - 1);
quickSort(num, i + 1, end);
}
int main()
{
soultion* sou = new soultion;
vector<int> st {6, 1, 2, 7, 9, 9, 3, 4, 5, 10, 8};
cout << " 排序前 :";
for (auto i : st)
{
cout << i << " ";
}
cout << endl;
sou->quickSort(st, 0 ,st.size() - 1);
cout << " 排序后 :";
for (auto i : st)
{
cout << i << " ";
}
cout << endl;
}