"Algorithm data structure Java implementation" binary lookup

Source: Internet
Author: User

1. Background

For example, an integer x is a set of numbers in a sequence of columns sorted by size, and we want to find the index position of x in the sequence.

For example, the sequence is arranged from small to large:

-3,-2,0,4,5,7,12,64

We want to find the position of the number 7, if it is a linear lookup, the time complexity is O (n), if you find with binary, the time complexity is O (log (n)), because each time the binary, the calculation of less than half, so take the logarithm.


2. Code
Package Algorithm_analysis;public class Bisearch {static int[] array={-3,-2,0,4,5,7,12,64}, public static void main ( String args[]) {   int left=0;   int right=array.length;   int center=0;   int k=7;     while (left<=right) {  center= (right+left)/2;   if ((array[center]-k) ==0) {  System.out.print (center);  break;   }   else{            if ((array[center]-k) >0) {                 right=center;            }                 else{                 Left=center;}}}}   Output Results 7

/********************************

* This article from the blog "Bo Li Garvin"

* Reprint Please indicate the source : Http://blog.csdn.net/buptgshengod

******************************************/



"Algorithm data structure Java implementation" binary lookup

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.