快速排序
快速排序算法核心思想,在快速排序过程中,通过一趟划分,可以把待排序区间分为两个子区间,然后分别对这两个子区间再进行同样的划分,这样的套娃机制我们常常使用递归算法解决比较轻松,不过也可以通过非递归的方法实现。比如我们下面讲到的非递归算法,分别使用了栈,还有队列实现,以栈为例,栈的作用就是在处理一个子区间的时候,保存产生的新的左、右区间,待一个区间处理完后,再从栈中取出另外一个子区间进行处理
- 递归算法实现
- 栈实现
- 队列实现
// 快速排序的两种实现方式1-递归2-非递归
#include <stdio.h>
using namespace std;
#include<iostream>
#include<queue>
queue<int>q;
#include<stack>
stack<int>s;
void print_data(int A[], int n){
// cout << "下标从0开始:";
for (int i = 0; i<n; i++) {
cout << A[i] << " ";
}
cout << endl << endl;
}
int do_quick_sort(int A[], int low, int high);
void quick_sort(int A[], int low, int high){
if (low<high) {
//返回中间位置
int mid = do_quick_sort(A, low, high);
// cout << "mid:" << mid << endl;
quick_sort(A, low, mid-1);
quick_sort(A, mid+1, high);
}
}
int do_quick_sort(int A[], int low, int high){
int temp = A[low];
while(low<high){
while(low<high && temp<=A[high])
high--;
A[low] = A[high];
while(low<high && temp>A[low])
low++;
A[high] = A[low];
}
A[high] = temp;
return high;
}
void quick_sort2(int A[], int low, int high){
s.push(low);
s.push(high);
int high1 = 0, low1 = 0;
while (!s.empty()) {
high1 = s.top();
s.pop();
low1 = s.top();
s.pop();
int mid = do_quick_sort(A, low1, high1);
if (low1<=mid-1) {
s.push(low1);
s.push(mid-1);
}
if (mid+1<=high1) {
s.push(mid+1);
s.push(high1);
}
}
}
void quick_sort3(int A[], int low, int high){
q.push(low);
q.push(high);
int high1 = 0, low1 = 0;
while (!q.empty()) {
low1 = q.front();
q.pop();
high1 = q.front();
q.pop();
int mid = do_quick_sort(A, low1, high1);
if (low1<=mid-1) {
q.push(low1);
q.push(mid-1);
}
if (mid+1<=high1) {
q.push(mid+1);
q.push(high1);
}
}
}
int main(){
cout << "welcome, to my world!" << endl;
int A[] = {5,3,6,8,2,6,9,73,985,211};
print_data(A, 10);
quick_sort(A, 0, 9);
print_data(A, 10);
quick_sort2(A, 0, 9);
print_data(A, 10);
quick_sort3(A, 0, 9);
print_data(A, 10);
return 0;
}
输出
welcome, to my world!
5 3 6 8 2 6 9 73 985 211
2 3 5 6 6 8 9 73 211 985
2 3 5 6 6 8 9 73 211 985
2 3 5 6 6 8 9 73 211 985
Program ended with exit code: 0