#include <stdio.h>

int binary_search(int arr[], int n, int x) { int l = 0, r = n-1, mid; while (l <= r) { mid = (l + r) / 2; if (arr[mid] == x) { return mid; } else if (arr[mid] < x) { l = mid + 1; } else { r = mid - 1; } } return -1; }

int main() { int arr[] = {1, 3, 5, 7, 9, 11, 13}; int n = sizeof(arr) / sizeof(int); int x = 7; int index = binary_search(arr, n, x); if (index != -1) { printf("%d is found at index %d.\n", x, index); } else { printf("%d is not found.\n", x); } return 0; }

写一个用c的二分排序

原文地址: https://www.cveoy.top/t/topic/97a 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录