最近又在看数据结构,贴两个经典的排序算法,标准C++实现。
快速排序:
#include<iostream>
using namespace std;
template<class T>
size_t Partition(T a[],size_t low,size_t high)
{
T 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;
}
template<class T>
void QSort(T a[],size_t low,size_t high)
{
if(low<high){
size_t pivotLoc=Partition(a,low,high);
QSort(a,low,pivotLoc-1);
QSort(a,pivotLoc+1,high);
}
}
template<class T>
void QSort(T a[],size_t size)
{
QSort(a,0,size);
}
int main()
{
int inta[]={7,1,3,4,5,10,2,6,9,8};
Partition(inta,0,9);
cout<<"The first partition result:"<<endl;
for(size_t i=0;i!=10;++i)
{
cout<<inta[i]<<" ";
}
cout<<endl<<"The sorted result:"<<endl;
QSort(inta,9);
for(size_t i=0;i!=10;++i)
{
cout<<inta[i]<<" ";
}
return EXIT_SUCCESS;
}
Shell排序:
#include<iostream>
using namespace std;
template<class T>
void ShellInsert(T a[],size_t a_size,size_t dk)
{
for(int i=dk;i!=a_size;++i){
cout<<i<<endl;
if(a[i]<a[i-dk]) {
T temp=a[i];
int j=i-dk;
for(;j>=0 && temp<a[j];j-=dk){
a[j+dk]=a[j];
}
a[j+dk]=temp;
}
}
}
template<class T>
void ShellSort(T a[],size_t a_size,size_t dlta[],size_t dlta_size)
{
for(int i=0;i!=dlta_size;++i)
ShellInsert(a,a_size,dlta[i]);
}
int main()
{
int inta[]={7,1,3,4,5,10,2,6,9,8};
int intb[]={49,38,65,97,76,13,27,49,55,4};
size_t dlta[]={5,3,2,1};
cout<<"The sorted result:"<<endl;
ShellSort(inta,10,dlta,4);
for(size_t i=0;i!=10;++i)
{
cout<<inta[i]<<" ";
}
return EXIT_SUCCESS;
}