Binary search of one-dimensional arrays

Source: Internet
Author: User

/**
* @param args
* @author Wangxianpeng
* Working principle:
* Binary search method is also called binary search method. Compares the keywords in the middle position of the array with the searched keywords.
* If the two are equal then the search succeeds; otherwise, the array is divided into former and two sub-arrays using intermediate positional records
* If the key in the middle position record is greater than the lookup keyword, the previous sub-array is further found
*, otherwise further find the following sub-array. Repeat the above process until it is found or not found.
*
Steps
* 1. Creates an array of arrays and initializes them statically.
*
* 2. Tip user belongs to number to find
*
* 3. The declaration begins subscript start, ends the subscript end, and the middle subscript middle and assigns values.
*
* 4. Declare the label index and assign the value to-1;
*
* 5. The formula for finding the intermediate coordinates is middle = (start + end)/2.
*
* 6.if (number = = Array[middle]) then the next index = middle; Break
*
* 7.if (number > Array[middle]) then start = Middle +1;
*
* 8.if (number < Array{middle]) then end = Middle-1;
*
* Using the While loop condition is (start <= end)
*
* Output Result: If index =-1 is not found
* Otherwise the output subscript
*/

public static void Main (string[] args) {
Scanner input = new Scanner (system.in);
SYSTEM.OUT.PRINTLN ("Light input a number");
int number = Input.nextint ();

int []array = {1,2,3,4,5,6,7,8,9};
int start = 0;
int end= array.length-1;
int middel = 0;
int index =-1;


while (start <= end) {


Middel = (start + end)/2;

if (number = = Array[middel]) {
index = middel+1;
Break
}
else if (number > Array[middel]) {
Start = Middel + 1;
}
else {
end = MIDDEL-1;
}
}

if (array (number) = =-1) {
System.out.println ("not find");
}


else {
System.out.println ("Find at" + Array (number));
}
}

Binary search of one-dimensional arrays

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.