将e插入到顺序表的适当位置上以保持该表的有序性
001 #define true 1
002 #define false 0
003 #define ok 1
004 #define error 0
005 #define infeasible -1
006 #define overflow -2
007 #define list_init_size 100
008 #define listincrement 10
009 #include<stdio.h>
010 #include<malloc.h>
011 typedef int ElemType;
012 typedef int Status;
013
014 typedef struct
015 {
016 ElemType *elem;//存储空间的基址,数组指针elem指示线性表的基地址
017 int length;
018 int listsize;//定义分配给顺序表的存储容量;
019 } SqList;
020
021 Status InitList(SqList*L)
022 {
023 (*L).elem=(ElemType*)malloc(list_init_size*sizeof(ElemType));
024 printf("顺序表基址为:%d/n",(*L).elem);
025 if(!(*L).elem)exit(overflow);
026 (*L).length=0;
027 (*L).listsize=list_init_size;
028 return ok;
029 }
030
031 Status DeleteK(SqList *L,int i,int k)
032 {
033 //本过程从顺序存储结构的线性表a中删除第i个元素起的k个元素
034 int j;
035 if(i<1||k<0||i+k>(*L).length) return infeasible;//参数不合法
036 else
037 {
038 for(j=i+k-2; j<=(*L).length-1&&i<=i+k-2; j++,i++)(*L).elem[i-1]=(*L).elem[j+1];
039 (*L).length=(*L).length-k;
040 return ok;
041 }
042
043 }
044
045 Status insert_suitable_position(SqList *L,ElemType e)
046 {
047 //将e插入到顺序表的适当位置上以保持该表的有序性;
048 int i,j;
049 for(i=0; i<=(*L).length-1; i++)//找到大于e的位置;
050 {
051 if((*L).elem[i]>e)break;
052 }
053 if(i>(*L).length-1)//插到尾巴的情况;
054 {
055 (*L).elem[(*L).length]=e;
056 (*L).length++;
057 return ok;
058 }
059 //插入到i-1位置;
060 for(j=(*L).length-1; j>=i-1; j--)
061 {
062 (*L).elem[j+1]=(*L).elem[j];
063 }
064 (*L).length++;
065 return ok;
066 }
067
068 Status insert_suitable_position_better(SqList *L,ElemType e)
069 {
070 //将e插入到顺序表的适当位置上以保持该表的有序性;
071 int j;
072 for(j=(*L).length;j>0,e<(*L).elem[j-1]; j--)
073 {
074 (*L).elem[j]=(*L).elem[j-1];
075 }
076 (*L).elem[j]=e;
077 (*L).length++;
078 return ok;
079 }
080
081 void main()
082 {
083
084 SqList L;
085 int i,j,e,n,m,k;
086 InitList(&L);
087 L.length=10;//将长度设为10,方便后面测试;
088 for(i=0; i<L.length; i++)
089 {
090 L.elem[i]=i;
091 }
092 for(j=0; j<L.length; j++)
093 {
094 printf("%d/t",L.elem[j]);
095 }
096 printf("/n插入的数字是?/n");
097 scanf("%d",&e);
098 insert_suitable_position_better(&L,e);
099 for(j=0; j<L.length; j++)
100 {
101 printf("%d/t",L.elem[j]);
102 }