• C语言二分查找


    #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
    ",low,high,a[low-1]);
    
        if (low - 1 >= 0 && a[low - 1] ==k)
        {
            return low-1;
        }
        return NoFound;
    }
  • 相关阅读:

    队列
    数据结构简介
    标准模板库
    类模板
    函数模板
    srvctl error
    FLASH BACK
    RAC 设置archive log模式
    CHAPTER 1 Architectural Overview of Oracle Database 11g
  • 原文地址:https://www.cnblogs.com/flashBoxer/p/9471527.html
Copyright © 2020-2023  润新知