binarySearch

 

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

  

posted @ 2023-11-17 10:48  ascertain  阅读(8)  评论(0编辑  收藏  举报