习题1.9 有序数组的插入 (20分)
思路分析:
将要插入的数字n和已经是递减排序好的数列元素进行比较,从左到右进行遍历,直到有一个元素小于小于n,记录位置为tempposition,然后将n右边的元素右移,将n插入到这个位置,注意其中判断数列是否满或者n是否与数列元素相同
bool Insert( List L, ElementType X )
{
int i =0;
int tempPosition;
while(L->Data[i]>X)
{
i++;
}
tempPosition = i;
if(L->Data[tempPosition]==X||(L->Last+1)>=MAXSIZE) return false;
for(i = L->Last; i>=tempPosition;i--)
{
L->Data[i+1] = L->Data[i];
}
L->Data[tempPosition] = X;
L->Last++;
return true;
}
注意下面这段代码(错误的)
for(i = 0; X<L->Data[i];i++)
{
tempPosition = i;
}
原因在于for循环里面的i无法存储小于n的元素的位置,for循环里面的 tempPosition会少一位,而while循环会准确记录该元素的位置