数据结构与算法(C++)--插入排序

低级排序:冒泡排序、选择排序、插入排序


void InsertionSort_2(T *a,int n);
template<class T>
void Insert(const T &e,T *a,int i);
int main()
{
double x[]={2.1,4,6.6,8,0,1,3,5,7,9};
int y[]={0,2,4,6,8,0,1,3,5,7,9};
InsertionSort(x,10);
    InsertionSort_2(y,10);
for(int i=1;i<=10;i++)
cout<<y[i]<<endl;
return 0;
}

template<class T>
void InsertionSort(T *a,int n)
{
  int in, out; //out=0这个人已经出去了,in是在外面排队的人,out是从房间里出去的人
  for(out=1;out<n;++out)  //房间里一共有这么多人
  {
T temp=a[out];
    in=out;
while(in>0 && a[in-1]>=temp) //比较、移动
    {
  a[in]=a[in-1];
  --in;
}
    a[in]=temp;
  }
}

template<class T>
void InsertionSort_2(T *a,int n)
{
  //a[0]用来保存排序使用,不能保存原始数据
for(int j=2;j<=n;++j)
{
T temp=a[j];
Insert(temp,a,j-1);
}
}

template<class T>
void Insert(const T & e,T *a,int i)
{
  a[0]=e;
while(e<a[i])
{
a[i+1]=a[i];
i--;
}
    a[i+1]=e;

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值