# Java Binary Search Algorithm

Source: Internet
Author: User

The beauty of programming lies in the beauty of algorithms. Let's first look at the binary search algorithm: The Hidden condition: binary search must be ordered, from small to large, or binary search can be performed only after sorting from large to small. Let's look at the code below:

`Package com.cn. daming; public class MainActivity {/*** @ param args */public static void main (String [] args) {int [] aInts = new int [] {1, 3, 5, 8, 11,14, 16,24, 37,47, 49,56, 63,83, 223}; // The sorting is from small to large int [] aInts2 = new int [] {322,243,211,156, 98,85, 79,68, 53,47, 38,24, 13, 6, 2}; // The sorting is from large to small // TODO Auto-generated method stub MainActivity main = new MainActivity (); System. out. println ("aInts the reault is:" + main. BinarySearch (aInts, 0, aInts. length, 24); System. out. println ("aInts2 the reault is:" + main. binarySearch2 (aInts2, 0, aInts2.length, 243);} // binary search for private int binarySearch (int [] a, int start, int len, int key) {int high = start + len, low = start-1, guess; while (high-low> 1) {guess = (high + low)/2; if (a [guess] <key) low = guess; else high = guess;} if (high = start + len) r Eturn ~ (Start + len); else if (a [high] = key) return high; else return ~ High;} // binary search from large to small private int binarySearch2 (int [] a, int start, int len, int key) {int high = start + len, low = start-1, guess; while (high-low> 1) {guess = (high + low)/2; if (a [guess]> key) low = guess; else high = guess;} if (high = start + len) return ~ (Start + len); else if (a [high] = key) return high; else return ~ High ;}}`

Related Keywords:

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.