贴两个经典的排序算法

最近又在看数据结构,贴两个经典的排序算法,标准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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值