-1. 初始化:
```c
int arr[5] = {1, 2, 3, 4, 5}; // 初始化为1, 2, 3, 4, 5
int arr[5] = {0}; // 初始化为0
```
2. 访问:
```c
int arr[5] = {1, 2, 3, 4, 5};
int a = arr[0]; // 获取第一个元素的值
```
3. 遍历:
```c
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
```
4. 求长度:
```c
int arr[5] = {1, 2, 3, 4, 5};
int len = sizeof(arr) / sizeof(arr[0]);
printf("数组长度为%d", len);
```
5. 复制:
```c
int arr1[5] = {1, 2, 3, 4, 5};
int arr2[5];
for (int i = 0; i < 5; i++) {
arr2[i] = arr1[i];
}
```
6. 比较:
```c
int arr1[5] = {1, 2, 3, 4, 5};
int arr2[5] = {1, 2, 3, 4, 5};
int isEqual = 1;
for (int i = 0; i < 5; i++) {
if (arr1[i] != arr2[i]) {
isEqual = 0; // 只要有一个元素不相等就不相等
break;
}
}
if (isEqual) {
printf("两个数组相等");
} else {
printf("两个数组不相等");
}
```
7. 排序:
```c
int arr[5] = {5, 3, 1, 4, 2};
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
```
8. 查找:
线性查找:
```c
int arr[5] = {1, 2, 3, 4, 5};
int target = 3;
int index = -1;
for (int i = 0; i < 5; i++) {
if (arr[i] == target) {
index = i;
break;
}
}
if (index != -1) {
printf("找到了,下标为%d", index);
} else {
printf("没找到");
}
```
二分查找:
```c
int arr[5] = {1, 2, 3, 4, 5};
int target = 3;
int left = 0, right = 4;
int index = -1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) {
index = mid;
break;
} else if (arr[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
if (index != -1) {
printf("找到了,下标为%d", index);
} else {
printf("没找到");
}
```
9. 插入:
```c
int arr[5] = {1, 2, 3, 4, 5};
int insertValue = 6;
int insertIndex = 2;
for (int i = 4; i >= insertIndex; i--) {
arr[i + 1] = arr[i];
}
arr[insertIndex] = insertValue;
for (int i = 0; i < 6; i++) {
printf("%d ", arr[i]);
}
```
10. 删除:
```c
int arr[5] = {1, 2, 3, 4, 5};
int deleteIndex = 2;
for (int i = deleteIndex; i < 4; i++) {
arr[i] = arr[i + 1];
}
for (int i = 0; i < 4; i++) {
printf("%d ", arr[i]);
}
```
标签:index,arr,语言,int,mid,++,数组,printf,操作 From: https://www.cnblogs.com/full-stack-linux-new/p/17342475.html