2路插入排序

 #include <iostream>
using namespace std;

void BRInsertSort( int from[], int to[], int n, int* first, int *final);

void main()
{
 int i,first, final;
 int a[6]={0,20,18,21,16,23};
 int b[6];
 for (i=1; i<=5; i++)
  cout << a[i] << " ";
 cout << endl;
 BRInsertSort(a, b, 5, &first, &final);
 for (i=first; i<=5; i++)
  cout << b[i] << " ";
 for (i = 1; i<=final; i++)
  cout << b[i] << " ";
 cout << endl;
}

void BRInsertSort(int from[], int to[], int n,int* first, int *final)
{
 int i;//用作外层遍历循环
 *first=1, *final = 1;//用作辅助索引
    int j, k;
 to[1] = from[1];//选择第一个元素作为中间项
 for (i = 2; i <= n; i++)
 {
  if (from[i] > to[1])//插入到前面
  {
   for (j=1; j<= *final; j++)//遍历找位置的过程
   {
    if (from[i] < to[j])
     break;//此时j+1位置正式要插入的位置
   }
   
   for (k=*final; k>=j; k--)//移动的过程
    to[k+1] = to[k];
   to[j] = from[i];
   (*final)++;
  }
  else if (from[i] < to[1])//插到后面
  {
   if(*first==1)
   {
    (*first) = n;
    to[*first] = from[i];
    continue;
   }
   for (j=*first; j<=n; j++)
   {
    if (from[i] < to[j])
     break;//此时j-1的位置就是要插入的位置
   }
   for (k=*first; k<=j-1; k++)//移动的过程
    to[k-1] = to[k];
   to[j-1] = from[i];
   (*first)--;
  }
 }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值