#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)--;
}
}
}