Binary Search Algorithm

Source: Internet
Author: User

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 ();}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.