Home  >  Article  >  Binary search algorithm c language

Binary search algorithm c language

angryTom
angryTomOriginal
2019-10-22 15:39:378861browse

Binary search algorithm c language

Binary search algorithm c language

Binary search is half search, its basic idea Yes: First select the record in the middle of the table, compare its key with the given key key, if they are equal, the search is successful; if the key value is greater than the key value, the element you are looking for must be in the right subtable , then continue the halved search on the right subtable: if the key value is smaller than the key value, the element you are looking for must be in the left subtable, and continue the halved search on the left subtable. This process is repeated until the search succeeds or fails (or the search range is 0).

Implementation code:

(1) Custom function binary_search() to implement binary search.

(2) The main() function serves as the entry function of the program. The program code is as follows:

#include <stdio.h>
int binary_search(int key,int a[],int n) //自定义函数binary_search()
{
    int low,high,mid,count=0,count1=0;
    low=0;
    high=n-1;
    while(low<high)    //査找范围不为0时执行循环体语句
    {
        count++;    //count记录査找次数
        mid=(low+high)/2;    //求中间位置
        if(key<a[mid])    //key小于中间值时
            high=mid-1;    //确定左子表范围
        else if(key>a[mid])    //key 大于中间值时
            low=mid+1;    //确定右子表范围
        else if(key==a[mid])    //当key等于中间值时,证明查找成功
        {
            printf("查找成功!\n 查找 %d 次!a[%d]=%d",count,mid,key);    //输出査找次数及所査找元素在数组中的位置
            count1++;    //count1记录查找成功次数
            break;
        }
    }
    if(count1==0)    //判断是否查找失敗
        printf("查找失敗!");    //査找失敗输出no found
    return 0;
}
int main()
{
    int i,key,a[100],n;
    printf("请输入数组的长度:\n");
    scanf("%d",&n);    //输入数组元素个数
    printf("请输入数组元素:\n");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);    //输入有序数列到数组a中
    printf("请输入你想查找的元素:\n");
    scanf("%d",&key);    //输入要^找的关键字
    binary_search(key,a,n);    //调用自定义函数
    printf("\n");
    return 0;
}

The above is the detailed content of Binary search algorithm c language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn