码迷,mamicode.com
首页 > 编程语言 > 详细

C语言二分查找

时间:2018-08-13 23:55:18      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:ntb   style   lse   base   数组   序列   相等   bsp   print   

#include <stdio.h>

/*
二分查找条件: 1、有序序列  2、数据在数组中
*/


int baseBinarySearch(int a[],int h,int k)
{
    int low=0;
    int high=h;
    int mid =0;
    int NoFound = -1;
    while (low <= high)
    {
        mid = low + (high-low) /2 ;
        if ( k < a[mid] )
        {
            high = mid - 1;
        }
        else if ( k > a[mid] )
        {
            low = mid + 1;
        }
        else
        {
            return mid;
        }
    }
    return NoFound;
}


//查找第一个相等的元素
int FirstElementBinSearch(int a[],int h,int k)
{
    int low=0;
    int high=h;
    int mid =0;
    int NoFound = -1;
    while (low <= high)
    {
        mid = low + (high-low) /2 ;
        if ( k <= a[mid] )
        {
            high = mid - 1;
        }
        else
        {
            low = mid + 1;
        }
    }
    return low <= h ? low : NoFound;
}

//查找最后一个相等的元素low

int LastElementBinSearch(int a[],int h,int k)
{
    int low=0;
    int high=h;
    int mid =0;
    int NoFound = -1;
    while (low <= high)
    {
        mid = low + (high-low) /2 ;
        if ( k >= a[mid] )
        {
           low = mid + 1 ;
        }
        else
        {
            high = mid -1 ;
        }
    }
    printf("%d %d %d\n",low,high,a[low-1]);

    if (low - 1 >= 0 && a[low - 1] ==k)
    {
        return low-1;
    }
    return NoFound;
}

 

C语言二分查找

标签:ntb   style   lse   base   数组   序列   相等   bsp   print   

原文地址:https://www.cnblogs.com/flashBoxer/p/9471527.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!