Find premises: array elements ordered
requirements: Finding the index of an element
Code implementation:
public class Test_erfenfa {public
static void Main (string[] args) {
int[] arr = {11,22,33,44,55,66,77};
int i = GetIndex (arr,33);
System.out.println (i);
}
public static int GetIndex (int[] arr, int value) {
int min = 0;
int max = arr.length-1;
int mid = (min + max)/2;
while (Arr[mid]!= value) {/ /when the median value is not equal to the value to be found, start the loop lookup
if (Arr[mid] < value) { //when the median value is less than the value to be found
min = mid + 1; The smallest index changes
}else if (Arr[mid] > value) { //when the median value is greater than the value to be found
max = mid-1; Maximum index change
}
mid = (min + max)/2; Regardless of the maximum or minimum change, the intermediate index will change with the
if (min > Max) { //If the minimum index is greater than the maximum index, there is no possibility of a lookup
return-1; Returns-1
}
} return
mid;
}