调了一个多小时才调好
不说了,上源代码
/*
*Quick sort is a kind of algorithm which can sort quickly
*Time complexity is O(n*log n)
*The algorithm is based on divide and conquer to decrease duplicate computation
*First : We choose a pivot which usually is the first element in the array
* We set two pointers ,one points the start of the array ,the other points the end of the array
*Then we make all the elements are bigger than the pivot are at the left side of the pivot,
*the same as the smaller elements
*/
#ifndef _QUICKSORT_
#define _QUICKSOrT_
#include<iostream>
using namespace std;
template<typename E>void Swap(E& a , E &b)
{
E tmp = a;
a = b;
b = tmp;
}
template<typename E>
void quickSort (E* T , E low , E high )
{
if(high <= low){return;} //recursive base
//recursive
E pivot = T[low] ; //remember
E p = low ; //point 1
E q = high - 1 ; //point 2
while(p < q)
{
while(T[q] >= pivot && q > low ) {--q ;}
while(T[p] <= pivot && p < high - 1 ) {++p ;}
if(p < q){
Swap(T[p] , T[q]) ;
}
else break;
}
Swap(T[q] , T[low]);
//for(int i = 0 ;i < 100 ;i ++){cout<<T[i]<<" ";} //调试用的
cout<<endl;
quickSort (T , low , q );
quickSort (T , q + 1 , high);
}
#endif
主函数
#include<iostream>
#include<cstdlib>
#include<ctime>
#include"quickSort.h"
using namespace std;
int main()
{
int T [100];
srand(time(NULL));
for(int i = 0 ;i < 100 ; i++)
{
T[i] = rand() % 31 + 1;
cout<<T[i]<<" ";
}
cout<<endl;
quickSort(T, 0 , 100);
for(int i = 0 ;i < 100 ; i++)
{
cout<<T[i]<<" "; //调试用的
}
}
测试结果
总结
一定要注意边界处理,递归的时候要弄清上界和下界,注意左开右闭
[low,target) , target , [target+1,high)
因为一趟快排之后target的位置已经寻找到就不需要它了,把它当做边界
图中所展示的那样,每趟快排都定一个元素
与之对比的是归并排序,进行了归并