[Java source code] binary sorting array (half-fold) Search

Source: Internet
Author: User

For sorted arrays, the binary method is a simple and effective search method. The algorithm complexity is O (log2n). Code: [java] package alg; public class Bisection {public static int bisectionSearch (int value, int [] array) {int minIndex = 0; int curIndex = 0; int maxIndex = array. length-1; int count = 0; // used for calculating the number of cycles int result =-1; if (value = array [maxIndex]) {result = maxIndex ;} else if (value = array [minIndex]) {result = minIndex;} else {while (true) {// if both Same or adjacent. Because the values (except for the first time) of the two come from a value that has been compared with the value, this value is not in the array. If (2> maxIndex-minIndex) {result =-1; break;} curIndex = minIndex + (maxIndex-minIndex)/2; if (array [curIndex] = value) {result = curIndex; break;} else if (array [curIndex] <value) {minIndex = curIndex;} else {maxIndex = curIndex;} count ++;} System. out. println ("loops =" + count); return result;} public static void main (String [] args) {int num = 1000; int value = 0; int [] array = new int [num]; for (int I = 0; I <num; I ++) {array [I] = I;} www.2cto.com System. out. println ("value =" + value + "at index" + bisectionSearch (value, array) + "of array. ") ;}} Author: Pirate Leoblog: http://blog.csdn.net/pirateleoemail:codeevoship@gmail.com

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.