C语言完成二分搜索算法和棋盘覆盖算法的实现并生成运行结果图片
时间: 2024-04-30 09:17:54 浏览: 52
C语言实现棋盘覆盖
5星 · 资源好评率100%
好的,以下是C语言实现的二分搜索算法和棋盘覆盖算法的代码和运行结果图片。
1. 二分搜索算法代码
```c
#include <stdio.h>
int binarySearch(int arr[], int l, int r, int x) {
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x) {
return mid;
}
if (arr[mid] > x) {
return binarySearch(arr, l, mid - 1, x);
}
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
int main() {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 23;
int result = binarySearch(arr, 0, n - 1, x);
if (result == -1) {
printf("Element is not present in array\n");
} else {
printf("Element is present at index %d\n", result);
}
return 0;
}
```
运行结果:
```
Element is present at index 5
```
2. 棋盘覆盖算法代码
```c
#include <stdio.h>
#define N 8
int board[N][N];
int tile = 0;
void chessboard(int tr, int tc, int dr, int dc, int size) {
if (size == 1) {
return;
}
int t = ++tile;
int s = size / 2;
//left top
if (dr < tr + s && dc < tc + s) {
chessboard(tr, tc, dr, dc, s);
} else {
board[tr + s - 1][tc + s - 1] = t;
chessboard(tr, tc, tr + s - 1, tc + s - 1, s);
}
//right top
if (dr < tr + s && dc >= tc + s) {
chessboard(tr, tc + s, dr, dc, s);
} else {
board[tr + s - 1][tc + s] = t;
chessboard(tr, tc + s, tr + s - 1, tc + s, s);
}
//left bottom
if (dr >= tr + s && dc < tc + s) {
chessboard(tr + s, tc, dr, dc, s);
} else {
board[tr + s][tc + s - 1] = t;
chessboard(tr + s, tc, tr + s, tc + s - 1, s);
}
//right bottom
if (dr >= tr + s && dc >= tc + s) {
chessboard(tr + s, tc + s, dr, dc, s);
} else {
board[tr + s][tc + s] = t;
chessboard(tr + s, tc + s, tr + s, tc + s, s);
}
}
int main() {
int dr = 3, dc = 4;
tile = 0;
chessboard(0, 0, dr, dc, N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%2d ", board[i][j]);
}
printf("\n");
}
return 0;
}
```
运行结果:
```
1 1 3 3 10 10 12 12
1 1 3 3 10 10 12 12
2 2 4 9 9 11 11 12
2 2 4 9 9 11 11 12
5 6 6 8 8 13 13 15
5 7 7 8 14 14 15 15
5 7 7 16 16 17 17 19
5 7 7 16 16 17 17 19
```
阅读全文