设顺序表va中的数据元素递增有序1。试用C语言写一算法,将x插入到顺序表的适当位置上,以保持该表的有序性,请给我两个示例。
时间: 2023-05-28 15:07:02 浏览: 102
示例一:
```
#include <stdio.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int length;
} SqList;
void InsertElement(SqList *list, int x) {
int i, j;
for (i = 0; i < list->length; i++) {
if (list->data[i] > x) {
break;
}
}
for (j = list->length - 1; j >= i; j--) {
list->data[j + 1] = list->data[j];
}
list->data[i] = x;
list->length++;
}
int main() {
SqList list = {{1, 3, 5, 7}, 4};
int x;
printf("请输入要插入的元素:\n");
scanf("%d", &x);
InsertElement(&list, x);
printf("插入后的有序表:\n");
for (int i = 0; i < list.length; i++) {
printf("%d ", list.data[i]);
}
printf("\n");
return 0;
}
```
示例二:
```
#include <stdio.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int length;
} SqList;
void InsertElement(SqList *list, int x) {
int low = 0, high = list->length - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (list->data[mid] == x) {
return;
} else if (list->data[mid] < x) {
low = mid + 1;
} else {
high = mid - 1;
}
}
for (int i = list->length - 1; i >= low; i--) {
list->data[i + 1] = list->data[i];
}
list->data[low] = x;
list->length++;
}
int main() {
SqList list = {{1, 3, 5, 7}, 4};
int x;
printf("请输入要插入的元素:\n");
scanf("%d", &x);
InsertElement(&list, x);
printf("插入后的有序表:\n");
for (int i = 0; i < list.length; i++) {
printf("%d ", list.data[i]);
}
printf("\n");
return 0;
}
```
阅读全文