//测试案例:49 38 65 97 76 13 27 49
#include<iostream>
#include<ctime>
#include<stdlib.h>
using namespace std;
//==================================================================================================================
//2.3快速排序
/*
1.选择待排序的表中第一个记录作为枢纽,枢纽记录暂时记录在r[0]上,设2个指针low和high,分别指向下界,上界,low=1,high=length
2.从最右向左依次搜索,找到第一个关键字比枢纽关键字privotkey小的记录,将其移到low处,具体:
当low<high时,若high处的值比privotkey的值大或等,左移high指针,否则high记录给予privotkey
3.从最左向右依次搜索,找到第一个关键字比枢纽关键字privotkey大的记录,将其移到high处,具体:
当low<high时,若low处的值比privotkey的值小或等,右移high指针,否则low记录给予high
4.重复上述2,3步骤,直到low==high,原表分成2个子表
*/
//特点:取决于递归树的深度,时间复杂度o(nlog2n),不稳定,适合顺序结构,适合无序,n大的情况
//2.3.1找到枢纽,从大到小
int Partition(int A[], int low, int high, int length) {
int privotkey = A[low];
while (low < high) {
while (low < high && A[high] >= privotkey)
high--;
A[low] = A[high];
while (low < high && A[low] <= privotkey)
low++;
A[high] = A[low];
}
A[low]=privotkey ;
return low;
}
//2.3.2排序
void Qsort(int A[], int low, int high, int& length) {
if (low < high) {
int pivotloc = Partition(A, low, high, length);
Qsort(A, low, pivotloc - 1, length);
Qsort(A, pivotloc + 1, high, length);
}
}
//算法分析
/*
时间复杂度
(1)趟数取决于递归树的深度
(2)最好情况,类似折半查找
(3)最坏情况:已经排好序
平均:O(n*log2n)
空间复杂度
递归,需要栈
最坏o(n),最好o(log2n)
特点:
(1)记录非顺次的移动导致不稳定
(2)排序过程中需要定义上下界,适合顺序结构
(3)当N很大,无序时,最适合
*/
int main() {
int* a = new int[9];
int length = 8;
srand(unsigned(time(NULL)));
for (int i = 1; i <= 8; i++) {
// a[i]=rand()% 90 + 10;
cin >> a[i];
}
cout << "==============" << endl;
cout << "快速排序:" << endl;
cout << "==============" << endl;
cout << "before sort:" << ends;
for (int i = 1; i <= length; i++) {
cout << a[i] << " ";
}
cout << endl;
Qsort(a, 1, length, length);
cout << "after sort:" << ends;
for (int i = 1; i <= length; i++) {
cout << a[i] << " ";
}
cout << endl;
delete a;
a = NULL;
}