首页 > 其他分享 >binarySearch

binarySearch

时间:2023-11-17 10:55:54浏览次数:33  
标签:return int mid binarySearch low array

 

Java

while

public class A {
    public static int binarySearch(int[] array, int aim) {
        int low = 0, high = array.length - 1, mid;
        while (low <= high) {
            mid = (low + high) / 2;
            if (aim < array[mid]) {
                high = mid - 1;
            } else if (aim > array[mid]) {
                low = mid + 1;
            } else {
                return mid;
            }
        }
        return -(low + 1);
    }

    public static void main(String[] args) {
        int[] array={1,3,5,8};
        System.out.println(binarySearch(array,9));
    }
}

  

recursion

public class A {
    public static int binarySearch(int[] array, int low, int high, int aim) {
        if (low > high) {
            return -(low + 1);
        }
        int mid = (low + high) / 2;
        if (aim < array[mid]) {
            return binarySearch(array, low, mid - 1, aim);
        } else if (aim > array[mid]) {
            return binarySearch(array, mid + 1, high, aim);
        } else {
            return mid;
        }
    }

    public static void main(String[] args) {
        int[] array = {1, 3, 5, 8};
        System.out.println(binarySearch(array, 0, array.length - 1, 9));
    }
}

 

Go

while

package main

func main() {
	var array = []int{1, 3, 5, 8}
	println(binarySearch(array, 9))
}
func binarySearch(array []int, aim int) int {
	var (
		low  = 0
		high = len(array) - 1
		mid  int
	)
	for low <= high {
		mid = (low + high) / 2
		if aim < array[mid] {
			high = mid - 1
		} else if aim > array[mid] {
			low = mid + 1
		} else {
			return mid
		}
	}
	return -(low + 1)
}

  

recursion

package main

func main() {
	var array = []int{1, 3, 5, 8}
	println(binarySearch(array, 0, len(array)-1, -1))
}

func binarySearch(array []int, low, high, aim int) int {
	if low > high {
		return -(low + 1)
	}
	mid := (low + high) / 2
	if aim < array[mid] {
		return binarySearch(array, low, mid-1, aim)
	} else if aim > array[mid] {
		return binarySearch(array, mid+1, high, aim)
	} else {
		return mid
	}
}

  

标签:return,int,mid,binarySearch,low,array
From: https://www.cnblogs.com/dissipate/p/17838154.html

相关文章

  • Arrays.binarySearch 详解
    Arrays.binarySearch详解前提:非降序排序数组binarySearch(Object[]a,Objectkey)a:待搜索的数组key:要搜索的值逻辑条件可以找到:返回一个>=0的索引找不到:【从1开始计数】在数组范围内,返回-(key将要插入的位置)不在范围内:返回-1或者-(len+1)......
  • BinarySearch
    packageBisectionMethod;/***704.二分查找*给定一个n个元素有序的(升序)整型数组nums和一个目标值target,写一个函数搜索nums中的target,*如果目标值存在返回下标,否则返回-1。*//***思路:设定左右指针*找出中间位置,并判断该位置值是否等于target*nums[......
  • Arrays方法之binarySearch():二叉搜索算法搜索指定的int数组的指定值
    以下直接抄写释义:publicstatic int binarySearch(int[] a,int key)使用二叉搜索算法搜索指定的int数组的指定值。 在进行此调用之前,必须对数组进行排序(如sort(int[......