binary search Algorithm
definition
The binary lookup algorithm is a search algorithm that finds a particular element in an ordered array. The search process begins with the middle element of the array, and if the intermediate element is exactly the element to be found, the search process ends, and if a particular element is greater than or less than the middle element, it is found in the half of the array greater than or less than the middle element, and is compared with the beginning of the intermediate element. If an array of steps is empty, the representation cannot be found. Each comparison of this search algorithm reduces the search scope by half. Binary search reduces the search area by half, with a time complexity of 0(LOGN).
Complexity of Time
O (LOGN)
Code
Package com.sprd.test.algorithm;
Import Java.util.Scanner; /** * Copyright TJ spreadtrum TEST_AF All right Reserved * * @author: Hui.qian Created on November 27, 2014 morning 9:37:20 D Escription: */public class BinarySearch {public int find (int[] data, int b) {if (data.length = = 0) {System.out
. println ("The current array does not have this number");
return-1;
} int length = Data.length;
int index = LENGTH/2;
int center = Data[index];
if (center = = b) {return index;
} else if (center < b) {int[] right = new INT[LENGTH-LENGTH/2-1];
for (int i = 0; i < right.length; i++) {Right[i] = Data[index + 1 + i];
} return index + find (right, b) + 1;
} else {int[] left = new INT[LENGTH/2];
for (int i = 0; i < left.length; i++) {left[i] = Data[i];
} return find (left, b);
}} public int findrecur (int start, int end, int b) {return 0;
public static void Main (string[] args) {int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9}; Scanner Scanner = New Scanner (system.in);
System.out.println ("array:");
Print (a);
while (true) {Integer b = 0;
System.out.println ("Please enter the number you are looking for:");
b = Scanner.nextint ();
Long start = System.currenttimemillis ();
int index = new BinarySearch (). Find (A, (int) b);
System.out.println (b + "index:" + index);
Long end = System.currenttimemillis ();
SYSTEM.OUT.PRINTLN ("Time Consuming:" + (End-start)); }} public static void print (int[] datas) {for (int i = 0; i < datas.length; i++) {System.out.print (datas[
I] + "");
} System.out.println ("");
}
}
Output
Array:
1 2 3 4 5 6 7 8 9
Please enter the number you are looking for:
9
9 in the index: 8
Please enter the number you are looking for:
7
7 index: 6
Please enter the number you are looking for:
0 the
current array does not have this number
0 index:-1
Please enter the number you are looking for:
1
1 index: 0
Please enter the number you want to find: