Step 1 : Find the middle element of array. using ,
middle = initial_value + end_value / 2 ;
Step 2 : If middle = element, return ‘element found’ and index.
Step 3 : if middle > element, call the function with end_value = middle - 1 .
Step 4 : if middle < element, call the function with start_value = middle + 1 .
Step 5 : exit.
二分搜索算法的实现函数使用了反复调用函数。这个调用可以有两种类型:
- 迭代
- 递归
迭代调用是多次循环同一段代码。
递归调用是反复调用同一个函数。
使用迭代调用实现二分搜索的程序
示例
演示
#include
int iterativeBinarySearch(int array[], int start_index, int end_index, int element){
while (start_index = start_index){
int middle = start_index + (end_index - start_index )/2;
if (array[middle] == element)
return middle;
if (array[middle] > element)
return recursiveBinarySearch(array, start_index, middle-1, element);
return recursiveBinarySearch(array, middle+1, end_index, element);
}
return -1;
}
int main(void){
int array[] = {1, 4, 7, 9, 16, 56, 70};
int n = 7;
int element = 9;
int found_index = recursiveBinarySearch(array, 0, n-1, element);
if(found_index == -1 ) {
printf("Element not found in the array ");
}
else {
printf("Element found at index : %d",found_index);
}
return 0;
}
登录后复制
输出
Element found at index : 3
登录后复制
以上就是二分搜索(递归和迭代)在C程序中的实现的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!