写一个c语言程序包括数组的查找、插入、删除、排序
时间: 2024-09-25 16:04:31 浏览: 48
在 C 语言中编写一个包含数组查找、插入、删除和排序的基本操作的程序,可以分为以下几个步骤:
1. 定义结构体(如果数据有特定结构的话),例如 `typedef struct` 表示一个整数数组的数据结构:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int* data;
int size;
} IntArray;
```
2. 初始化数组(创建结构体实例并分配内存):
```c
IntArray array;
array.size = 5; // 假设初始大小为5
array.data = malloc(array.size * sizeof(int));
```
3. 插入操作:
```c
void insert(IntArray* arr, int value) {
if (arr->size == array.capacity) {
arr->capacity *= 2; // 当满时扩容
arr->data = realloc(arr->data, arr->capacity * sizeof(int));
}
arr->data[arr->size++] = value;
}
```
4. 查找操作:
```c
int search(IntArray* arr, int target) {
for (int i = 0; i < arr->size; i++) {
if (arr->data[i] == target) {
return i;
}
}
return -1; // 如果未找到返回-1
}
```
5. 删除操作:
```c
void delete(IntArray* arr, int index) {
if (index >= 0 && index < arr->size) {
memmove(&arr->data[index], &arr->data[index + 1], (arr->size - index - 1) * sizeof(int));
arr->size--;
}
}
```
6. 排序操作(这里我们选择冒泡排序作为例子):
```c
void sort(IntArray* arr) {
int temp;
for (int i = 0; i < arr->size - 1; i++) {
for (int j = 0; j < arr->size - 1 - i; j++) {
if (arr->data[j] > arr->data[j + 1]) {
temp = arr->data[j];
arr->data[j] = arr->data[j + 1];
arr->data[j + 1] = temp;
}
}
}
}
```
7. 清理资源(记得释放内存):
```c
void destroy(IntArray* arr) {
free(arr->data);
arr->size = 0;
arr->data = NULL;
}
```
以上就是基本的数组操作函数,你可以根据需要组合使用。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![ppt](https://img-home.csdnimg.cn/images/20241231044937.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044947.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)