2020-06-12//(C语言)数据结构插入排序--折半插入排序

//折半插入排序

include

include

define MAXSIZE 100

typedef struct SqList
{
int r[MAXSIZE + 1];
int length;
} SqList;
void BInsertSort(SqList *L) //对顺序表L做折半插入排序
{
int low, high, m;
for (int i = 2; i <= L->length; i++)
{
L->r[0] = L->r[i]; //将待插入的记录暂存到监视哨中
low = 1;
high = i - 1; //查找区间初值
while (low <= high) //在r[low]和r[high]中折半查找插入的位置
{
m = (low + high) / 2; //折半
if (L->r[0] < L->r[m])
{
high = m - 1; //插入点在前一子表
}
else
{
low = m + 1; //插入点在后一子表
}
}
for (int j = i - 1; j >= high + 1; j--)
{
L->r[j + 1] = L->r[j]; //记录后移
}
L->r[high + 1] = L->r[0]; //将r[0]即原r[i],插入到正确位置
}
}
int main()
{
SqList *L;
L = (SqList *)malloc(sizeof(SqList));
int i;
printf("请输入长度:");
scanf("%d", &L->length);
printf("请输入元素:");
for (i = 1; i <= L->length; i++)
{
scanf("%d", &L->r[i]);
}
printf("排序前:");
for (i = 1; i <= L->length; i++)
{
printf("%d ", L->r[i]);
}
printf("\n");
printf("排序后:");
BInsertSort(L);
for (int i = 1; i <= L->length; i++)
{
printf("%d ", L->r[i]);
}
printf("\n");
}

你可能感兴趣的:(2020-06-12//(C语言)数据结构插入排序--折半插入排序)