Binary search java Implementation and time complexity, binaryjava
Overview
In an sorted array seq, binary search is used.VIf the range of this array is [low... high], we wantVIn this range. The search method is to take the value in the middle of low to high. We assume thatM, To followVComparedM>V, Indicating what we are lookingVThe first half of the forward array seq; otherwise, the second half is located. Whether in the front half or the back half, fold that part for another half search. repeat this process and findVValue.
To achieve binary search, you can use loops or recursion.
Java Implementation Loop
public static int iterativeSearch(int v, int[] seq) { int low = 0, high = seq.length - 1; while (low < high) { int mid = (low + high) / 2; int m = seq[mid]; if (v == m) { return mid; } else if (v > m) { low = mid + 1; } else { high = mid - 1; } } return -1; }
}Recursion
public static int recursionSearch(int v, int low, int high, int[] seq) { if (low > high) return -1; int mid = (low + high) / 2; int m = seq[mid]; if (v == m) { return mid; } else if (v > m) { return recursionSearch(v, mid + 1, high, seq); } else { return recursionSearch(v, low, mid - 1, seq); } }}Java 8 native implementation
private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; int midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. }Time Complexity
For example, there are n elements in total, and the interval size for each query is n, n/2, n/4 ,..., N/2 ^ k (the number of remaining elements in the next operation), where k is the number of cycles.
Since n/2 ^ k is rounded to> = 1, that is, n/2 ^ k = 1,
Obtain k = log2n (base on 2, logarithm of n), so the time complexity can be expressed as O () = O (logn)