Half-lookup,
Small knowledge points, easy to understand for beginners, clear remarks, simple and clear. Requirements: 1. in order, ascending and descending order. 2. Locate an element in the array. If no element exists, return-1.
// Package name package test1111; public class Demo2 {public static void main (String [] args) {// The first is an sorted array (ascending or descending) int [] arr = {11, 23, 40, 45, 59,65, 99}; // search for the number 45int index = getIndex (arr, 65); // obtain the value System. out. println ("index =" + index); // index = 5} public static int getIndex (int [] arr, int key) {int minIndex = 0; // minimum subscript int maxIndex = arr. length-1; // maximum subscript int midIndex = (maxIndex + minIndex)/2; // intermediate subscript while (key! = Arr [midIndex]) {// when the median and key are different, enter the loop to obtain a new set of numbers. if (key> arr [midIndex]) {// The key is greater than the median value, the minimum subscript of the new value is equal to the intermediate subscript + 1 minIndex = midIndex + 1;} else {// key is smaller than the intermediate value, and the obtained maximum subscript is equal to the intermediate subscript-1 maxIndex = midIndex-1 ;} if (maxIndex <minIndex) {// The maximum subscript is smaller than the minimum subscript to prove that the value does not exist return-1; // If no result is returned,-1} // The intermediate subscript midIndex = (maxIndex + minIndex)/2;} return midIndex; // always return the subscript of the number in the middle of the array }}