- 设顺序表va中的数据元素递增有序。试写一算法,将x插入到顺序表的适当位置上,且保持表的有序性。
#include <iostream>
#include<stdio.h>
#define LIST_INIT_SIZE (8)
typedef struct {
int *elem; /*存储空间基址*/
int length; /*当前长度*/
int listsize;/*允许的最大存储容量*/
}SqList;
void insert(SqList *S, int i) {
if (S->length >= S->listsize) {
printf_s("error\n");
}
else {
int * q=S->elem + S->length-1,*p= S->elem + S->length;
for (; q >= S->elem ; q--) {
if (i < *q && q!=S->elem) {
*p = *q;
p--;
}
else if(q != S->elem) {
*p = i;
S->length++;
break;
}
else {
*p = *q;
*q = i;
S->length++;
break;
}
}
}
}
void print(SqList* S, int length) {
for (int* p = S->elem; p < S->elem + S->length; p++) {
printf_s("%d ", *p);
}
}
int main()
{
SqList S = { NULL, 0, LIST_INIT_SIZE };
int Array[LIST_INIT_SIZE] = { 5, 10, 26, 30,34,35,36,37 }, num = 8;
S.elem = Array;
S.length = num;
insert(&S, 33);
print(&S, S.length);
}