Java Binary Lookup algorithm

Source: Internet
Author: User

Algorithm: It is suitable to use this method when the amount of data is large. when searching by binary method, the data need to be ordered and not duplicated . Basic idea: Assume that the data is sorted in ascending order, for a given value x, from the middle of the sequence of the comparison, if the current position value equals X, then the search succeeds; if x is less than the current position value, the first half of the sequence is searched, and if x is greater than the current position, the second half of the series is searched until

Suppose there is an array {

20,21,22,23,24,25,26,27
public class Twofindnum {public static void main (string[] args) {int []array=new int[]{20,21,22,23,24,25,26,27};  System.out.println (Search (array, 21)); If you find a value in an array, it returns the subscript for the element. otherwise returns-1. System.out.println (Search (array,30));}  Two-point lookup public static int search (int []array,int key) {int Start=0;int end=array.length-1; Length starting from 0, last subscript minus 1while (start<end) {int mid= (start+end)/2;if (Key<array[mid]) end=mid-1;else if (key>array[ Mid]) {start=mid+1;} Else{return Mid;}} return-1;}}


This article is from the "Star Moon Love" blog, please be sure to keep this source http://xuegodxingyue.blog.51cto.com/5989753/1950461

Java Binary Lookup algorithm

Related Article

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.