程序已经测试过,这是对照严蔚敏老师的数据结构书写的
//.h文件
#include<iostream>
using namespace std;
#define MAXSIZE 20//待排序的数据类型
typedef int KeyType;
typedef int InfoType;
typedef struct
{
KeyType key;
InfoType otherinfo;
} RedType;
typedef struct
{
RedType r[MAXSIZE + 1];
int length;
}SqList;
//.cpp文件
void BInsertSort(SqList &L);
void print(SqList &L);
int main()
{
SqList L;
int arr[MAXSIZE], x;
cout << "请输入您要输入多少数:" << endl;
cin >> x;
L.length = x;
cout << "请输入您要输入的数字" << endl;
for (int i = 1; i <= x; i++)
{
cin >> arr[i];
L.r[i].key = arr[i];
}
BInsertSort(L);
system("pause");
return 0;
}
void BInsertSort(SqList &L)
{//对顺序表L做折半插入排序
int i, j, m, low, high;
for (i = 2; i <= L.length; ++i)
{
L.r[0] = L.r[i];
low = 1;
high = i - 1;
while (low <= high)
{
m = (low + high) / 2;
if (L.r[0].key < L.r[m].key)
high = m - 1;
else
low = m + 1;
}
for (j = i - 1; j >= high + 1; --j)
L.r[j + 1] = L.r[j];
L.r[high + 1] = L.r[0];
}
print(L);
}
void print(SqList &L)
{
cout << "折半插入排序为:";
for (int m = 1; m <=L.length; m++)
cout << L.r[m].key<<" ";
cout << endl;
}