Binary search, also known as binary search, the advantage is that the comparison of less times, the search speed, average performance is good; its disadvantage is that the table is ordered table, and insert delete difficult. Therefore, the binary lookup method is suitable for frequently ordered lists that are infrequently changed. First, suppose that the elements in the table are sorted in ascending order, compares the keywords in the middle position record of the table to the lookup key, and if the two are equal, the search succeeds; otherwise, the table is divided into the preceding and the last two child tables using the middle position record, and the previous child table is further searched if the key of the middle position record is greater than the lookup keyword Otherwise, the next child table is further searched. Repeat the process until you find a record that satisfies the criteria, make the lookup successful, or until the child table does not exist, the lookup is unsuccessful.
/* Non-recursive binary lookup *
/public static int BinarySearch (int[] A, int x) {
int left = 0;
int right = A.length-1;
While [left <= right] {
int mid = (left+ right)/2;
if (x > A[mid]) {left
= mid+1/
else if (x < A[mid]) {Right
= mid-1;
} else {return
MID;
}
}
return-1;
}
Each iteration is within the loop of all work calls O (1), so the analysis needs to determine the number of cycles. The loop starts at Right-left=leng-1 and ends at right-left<=-1. The value of the right-left after each loop binary at least the value before the loop, so the maximum number of loops is [log (n-1)]+2. So: The time to run is O (log n), and the time complexity of recursion requires O (n).
Recursive algorithm for binary lookup public
static int bsearch (int[] A, int x, int left, int right) {
//index records find the subscript of an element, the initial state is -1
int Inde x =-1;
if (left <= right) {
int mid = (left+right)/2;
if (x > A[mid]) {
index = bsearch (A, X, mid+1, right);
} else if (x < A[mid]) {
index = bsearch (A, X, left , mid-1);
} else {return
mid;
}
}
return index;
}
In order to facilitate the test, here is the main method, here is the method.
public static void Main (string[] args) {
int[] a = {1, 3, 6, 8, 9, One,}; bsearch (A, 0, 0, a.length);
int res = bsearch (A,-1, 0, a.length-1);
if (res!=-1) {
System.out.println (subscript: + res);
} else {
System.out.println ("No this Element");
}
Because bloggers, recently have nothing to see Mark Allen Weiss "Data structure and algorithm analysis-java language description", read the first two chapters have insights, so want to write blog share, may be wrong place a lot of, especially for the time complexity of the analysis, grasp is not so good.