Binary Search and array binary search in Arrays

Source: Internet
Author: User

Binary Search and array binary search in Arrays

Package com. db2; import java. util. arrays;/*** Binary Search ** @ author denny the prerequisite array for binary search has been sorted out **/public class Demo4 {public static void main (String [] args) {int [] arr = {3, 1, 8, 2, 9,100, 33, 22, 11, 18, 14, 17, 15, 3}; // use Arrays. sort () sorting Arrays. sort (arr); System. out. println (Arrays. toString (arr); // returned result // int index = brinarySearch (arr, 99); int index = brinarySearch_2 (arr, 11); System. out. prin Tln ("index =" + index);}/** returns a subscript in the binary lookup. If it is-1, it means no */public static int brinarySearch (int [] arr, int key) {// array and number of queries int min = 0; // minimum subscript int max = arr. length-1; // The largest subscript int mid = (min + max)/2; // The middle subscript while (arr [mid]! = Key) {if (key> arr [mid]) {// The ratio of the intermediate number is min = mid + 1; // minimum subscript = intermediate subscript 1} else if (key <arr [mid]) {// smaller than intermediate number max = mid-1; // maximum subscript = intermediate subscript-1} if (max <min) {return-1;} mid = (min + max)/2; // calculate the intermediate subscript again} return mid;}/** returns a subscript in the binary search. If it is-1, it indicates that no */public static int brinarySearch_2 (int [] arr, int key) {// array and number of queries int min = 0; // minimum subscript int max = arr. length-1; // The largest subscript int mid = (min + max)/2; // The middle subscript while (min <= max) {if (key> arr [mid]) {min = mid + 1;} else if (key <arr [mid]) {max = mid-1 ;} else {return mid;} mid = (min + max)/2;} // No return-1 found ;}}

  

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.