注意,下面的算法中middle = (start+end)/2;会导致middle始终为偶数导致结果不对
所以后面补充了判断
/****************************************************************
题目:有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。
1. 程序分析:首先判断此数是否大于最后一个数,然后再考虑插入中间的数的情况,
插入后此元素之后的数,依次后移一个位置。
*****************************************************************/
#include <stdio.h>
int sort(void);
void main(void)
{
while(1)
{
sort();
}
}
int sort(void)
{
int array[120] = {10,20,30,40,50,60,70,80,90,100,110,120,130,140,150};
int num = 0;
int start = 0;
int end = 0;
int middle = 0;
int count =0;
int size = 0;
printf("Pls input search number!
");
scanf("%d",&num);
for(count = 1; count<120; count++)
{
if(0 == array[count])
{
size = count;
break;
}
}
if(0==size)
{
size = 120;
printf("The array is full ,can not insert an element !
");
return 0;
}
printf("array size is %d ",size);
start = 0;
end = size -1;
while(start<=end)
{
middle = (start+end)/2;
if(array[middle] < num)
{
start = middle+1;
}
else if(array[middle] > num)
{
end = middle -1;
}
else
{
break;
}
}
if(array[middle]>num)
{
if(1<=middle)
{
middle = middle -1;
printf("minus 1
");
}
}
else if(array[middle]<num)
{
middle = middle+1;
printf("add 1
");
}
printf("middle is %d
",middle);
for(count = size; count> middle;count--)
{
array[count] = array[count-1];
}
array[middle] = num;
for(count = 0; count < size+1; count++)
{
if(0==(count+1)%10)
{
printf("
");
}
printf("%3d ",array[count]);
}
printf(" ");
fflush(stdin);
}