用C语言写一个分治算法
时间: 2023-12-29 20:15:15 浏览: 79
以下是一个简单的分治算法代码示例,用于在数组中查找一个元素:
#include <stdio.h>
int binary_search(int arr[], int low, int high, int x) {
if (low > high) {
return -1;
}
int mid = (low + high) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] > x) {
return binary_search(arr, low, mid - 1, x);
} else {
return binary_search(arr, mid + 1, high, x);
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 6;
int result = binary_search(arr, 0, n - 1, x);
if (result == -1) {
printf("Element not found.");
} else {
printf("Element found at index %d.", result);
}
return 0;
}
阅读全文