Java Basic binary search algorithm

Source: Internet
Author: User

/*
* Binary Search Method:
Ideas
* Define three variables to record the largest, smallest, and intermediate index values in the lookup range, each time using an intermediate index value to compare to the target to be found, and if not, then narrow the search
* */
Prerequisite: The lookup sequence must be ordered
Int[] arr1 = {3,5,7,10,22,45,191};
Define three variables to record the bounds and middle position of the lookup, and initialize
int min = 0;
int max = Arr1.length;
int mid = (min + max)/2;
Define a variable that records the value of the element to find;
int target = 56;

while (true) {
if (Target>arr1[mid]) {
min = mid+1;
}else if (Target<arr1[mid]) {
max = mid-1;
}else if (Target==arr1[mid]) {
System.out.println ("found" + Target + "location is:" + mid);
Break
}
Mid = (max+min)/2;
if (max<min) {
System.out.println ("Did not find, the found element does not exist");
Break
}
}

Java Basic binary search algorithm

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.