算法设计:设顺序表va中的数据元素递增有序。试写一算法,将x插入到顺序表的适当位置上,且保持表的有序性。
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define TRUE 1;
#define FALSE 0;
#define OK 1;
#define ERROR 0;
#define INFEASIBLE - 1;
typedef int Status;
typedef int ElemType;
typedef struct {
ElemType* elem;
int length;
int listsize;
}SqList;
Status InitList_Sq(SqList& L) {
L.elem = (ElemType*)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if (!L.elem)
return ERROR;
L.length = 0;
L.listsize = LIST_INIT_SIZE;
return OK;
}
Status List_Add_Length(SqList& L) {
ElemType* newbase = (ElemType*)realloc(L.elem, (L.listsize + LISTINCREMENT) * sizeof(ElemType));
if (!newbase)
return ERROR;
L.elem = newbase;
L.listsize += LISTINCREMENT;
return OK;
}
Status List_Insert_one_Sq(SqList& L, ElemType x, int loc) {
int i;
for (i = L.length - 1; i > loc; i--) {
L.elem[i] = L.elem[i - 1];
}
L.elem[loc] = x;
return OK;
}
Status List_Insert_Sq(SqList &L, ElemType x) {
int loc=0;
L.length++;
if (L.length >= L.listsize)
List_Add_Length(L);
if (x <= L.elem[0]) {
List_Insert_one_Sq(L, x, loc);
return OK;
}
else if(x >= L.elem[L.length - 2]) {
loc = L.length - 1;
List_Insert_one_Sq(L, x, loc);
return OK;
}
for (int i = 1; i < L.length - 1; i++)
{
if (x <= L.elem[i])
{
loc = i;
List_Insert_one_Sq(L, x, loc);
return OK;
}
}
return ERROR;
}
int main() {
SqList va;
InitList_Sq(va);
va.length = 9;
int i;
for (i = 0; i < 9; i++) {
va.elem[i] = i;
}
ElemType x;
cin>>x;
List_Insert_Sq(va, x);
cout << "va=";
for (i = 0; i < va.length; i++) {
cout << va.elem[i]<<' ';
}
free(va.elem);
return 0;
}