Binary Search Algorithm
Question: Set a [0: n-1] to an array in sorted order. Rewrite the binary search algorithm so that when the search element x is not in the array, return the position I of the largest element smaller than x and the position j of the smallest element greater than x. When the search element is in the array, I and j are the same, and both are the positions of x in the array. Analyze the complexity of your programs.
Import java. util. arrays; import java. util. optional; public class Main {static int x; // The data to be searched // The shape parameter I, j is the array subscript, and arr is the original array, answer is the array storing the answer static void getij (int I, int j, int [] arr, int [] answer) {if (I> j) {// If x is not in the array, answer [0] = j; answer [1] = I; return;} int len = j-I + 1; // if you do not add 1, you can use if (x = arr [len/2 + I]) {// Arrays in the array. fill (answer, len/2 + I); // java api method, the function is to assign all elements in the array answer to len/2 + 1} else if (x <arr [len/2 + I]) {getij (I, len/2 + I-1, arr, answer);} else {getij (len/2 + I + 1, j, arr, answer );}} public static void main (String [] args) {custom region = new region (System. in); while (partial. hasNext () {int n = seconds. nextInt (); int [] arr = new int [n]; for (int I = 0; I <n; I ++) {arr [I] = random. nextInt ();} x = bytes. nextInt (); // The answer stores the array subscript I = answer [0]; j = answer [1] int [] answer = new int [2]; getij (0, n-1, arr, answer); // 0, n-1 are the subscript System of the array. out. println (answer [0] + "" + answer [1]);} bytes. close ();}}