2020苦瓜伦理片七仙

当前位置: 移动技术网 > IT编程>开发>C/C++ > C语言二分查找

C语言二分查找

42  人参与 | 时间:2018-08-15 | 我要评论

请记住本站备用网址:,收藏本站链接地址:http://www.sujpo.com

摄政王的毒医宠妃,心要让你听见简谱,僵尸物语txt下载

#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;
}

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复2020苦瓜伦理片七仙

2020苦瓜伦理片七仙相关的文章:

◎已有 0 人评论

移动技术网