本题要求将任一给定元素插入从大到小排好序的数组中合适的位置,以保持结果依然有序。 函数接口定义: 其中 |
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
typedef enum {false, true} bool;
typedef int ElementType;
typedef int Position;
typedef struct LNode *List;
struct LNode {
ElementType Data[MAXSIZE];
Position Last; /* 保存线性表中最后一个元素的位置 */
};
List ReadInput(); /* 裁判实现,细节不表。元素从下标0开始存储 */
void PrintList( List L ); /* 裁判实现,细节不表 */
bool Insert( List L, ElementType X );
int main()
{
List L;
ElementType X;
L = ReadInput();
scanf("%d", &X);
if ( Insert( L, X ) == false )
printf("Insertion failed.\n");
PrintList( L );
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例1:
5
35 12 8 7 3
10
输出样例1:
35 12 10 8 7 3
Last = 5
输入样例2:
6
35 12 10 8 7 3
8
输出样例2:
Insertion failed.
35 12 10 8 7 3
Last = 5
简单讲解
因为Data只是单纯的数组,所以所谓的插入,不过是循环位移罢了
nums[] = {1,2,4,5} , nums.length=4
插入 3 的话,只需要找到第一个比他大的数的下标,即 index=2 , nums[index] = 4
然后循环数组
for x in [nums.length , index , -1] : nums[x] = nums[x-1]
最后length++即可
至于是否插入成功的判断...见代码
bool Insert( List L, ElementType X )
{
int z,len=L->Last;
if(len==MAXSIZE-1) return false;
for(z=0;z<=len;z++){
if(L->Data[z]==X) return false;
if(L->Data[z]<X) break;
}
for(int z1=len+1;z1>=z;z1--){
if(z1==z) L->Data[z] = X;
else L->Data[z1] = L->Data[z1-1];
}
L->Last++;
return true;
}