折半查找法c语言函数
时间: 2023-12-10 19:34:23 浏览: 108
以下是一个使用折半查找法的C语言函数示例:
```c
int binarySearch(int arr[], int left, int right, int x) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] < x)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
```
该函数接受一个已排序的整数数组,数组的左右边界以及要查找的元素x作为参数。函数返回x在数组中的索引,如果x不在数组中,则返回-1。
相关问题
c语言指针折半查找法
折半查找法是一种高效的查找算法,也可以用于C语言中。下面是C语言指针折半查找法的实现:
```c
#include <stdio.h>
int binary_search(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {1, 3, 5, 7, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int target =5;
int index = binary_search(arr, n, target);
if (index == -1) {
printf("Target not found.\n");
} else {
printf("Target found at index %d.\n", index);
}
return 0;
}
```
上述代码中,`binary_search`函数实现了折半查找法,`main`函数中定义了一个有序数组`arr`,并在其中查找目标值`target`。如果找到了目标值,则返回其下标;否则返回-1。
c语言 编写折半查找法
折半查找法是一种高效的查找算法,适用于有序数组中查找特定元素的情况。以下是在C语言中实现折半查找法的代码:
```c
int binarySearch(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // 找到目标元素,返回索引
} else if (arr[mid] < target) {
left = mid + 1; // 目标元素在右半部分,更新左边界
} else {
right = mid - 1; // 目标元素在左半部分,更新右边界
}
}
return -1; // 未找到目标元素,返回-1
}
```
该函数接收一个有序数组arr、数组长度n和要查找的目标元素target,返回目标元素在数组中的索引。如果目标元素不在数组中,则返回-1。
例如,如果我们要查找数组arr中的元素target,可以调用以下代码:
```c
int index = binarySearch(arr, n, target);
```
其中n是数组arr的长度。如果目标元素在数组arr中,则index为其在数组中的索引;如果不在,则index为-1。
需要注意的是,该函数只适用于有序数组中查找目标元素。如果数组无序,需要先将其排序再进行查找。