动态内存顺序表的简单插入排序和二分法查找c语言
时间: 2023-06-12 19:06:22 浏览: 108
动态内存顺序表的简单插入排序:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *data; // 存储数据的数组
int length; // 当前存储数据的数量
int capacity; // 数组容量
} SeqList;
// 初始化顺序表
void initSeqList(SeqList *list, int capacity) {
list->capacity = capacity;
list->data = (int *)malloc(sizeof(int) * capacity); // 分配数组空间
list->length = 0; // 初始长度为0
}
// 插入元素
void insert(SeqList *list, int elem) {
if (list->length == list->capacity) { // 如果容量已满,扩容
list->data = (int *)realloc(list->data, sizeof(int) * (list->capacity + 10));
list->capacity += 10;
}
list->data[list->length++] = elem; // 插入元素
}
// 简单插入排序
void insertSort(SeqList *list) {
int i, j, temp;
for (i = 1; i < list->length; i++) {
temp = list->data[i];
for (j = i - 1; j >= 0 && list->data[j] > temp; j--) {
list->data[j + 1] = list->data[j];
}
list->data[j + 1] = temp;
}
}
// 输出顺序表
void print(SeqList *list) {
int i;
for (i = 0; i < list->length; i++) {
printf("%d ", list->data[i]);
}
printf("\n");
}
int main() {
SeqList list;
initSeqList(&list, 10);
insert(&list, 3);
insert(&list, 1);
insert(&list, 4);
insert(&list, 2);
printf("排序前:");
print(&list);
insertSort(&list);
printf("排序后:");
print(&list);
return 0;
}
```
动态内存顺序表的二分法查找:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *data; // 存储数据的数组
int length; // 当前存储数据的数量
int capacity; // 数组容量
} SeqList;
// 初始化顺序表
void initSeqList(SeqList *list, int capacity) {
list->capacity = capacity;
list->data = (int *)malloc(sizeof(int) * capacity); // 分配数组空间
list->length = 0; // 初始长度为0
}
// 插入元素
void insert(SeqList *list, int elem) {
if (list->length == list->capacity) { // 如果容量已满,扩容
list->data = (int *)realloc(list->data, sizeof(int) * (list->capacity + 10));
list->capacity += 10;
}
list->data[list->length++] = elem; // 插入元素
}
// 二分法查找
int search(SeqList *list, int elem) {
int left = 0, right = list->length - 1, mid;
while (left <= right) {
mid = (left + right) / 2;
if (list->data[mid] == elem) { // 找到元素
return mid;
} else if (list->data[mid] > elem) { // 在左侧继续查找
right = mid - 1;
} else { // 在右侧继续查找
left = mid + 1;
}
}
return -1; // 没有找到该元素
}
int main() {
SeqList list;
initSeqList(&list, 10);
insert(&list, 1);
insert(&list, 2);
insert(&list, 3);
insert(&list, 4);
printf("查找元素2的位置:%d\n", search(&list, 2));
printf("查找元素5的位置:%d\n", search(&list, 5));
return 0;
}
```
阅读全文