Problem statement: How will you do for binary search in java?
- public class BinarySearchExe {
- public static void main(String[] args) {
- int a[] = { 2, 4, 5, 6, 7, 9, 10 };
- int idx = binarySearch(a, 10);
- System.out.println(idx);
- } // end of main
- static int binarySearch(int a[], int key) {
- int start = 0, end = a.length - 1;
- while (start <= end) {
- int mid = (start + end) / 2;
- if (key == a[mid]) {
- return mid;
- } else if (key > a[mid]) {
- start = mid + 1;
- } else {
- end = mid - 1;
- }
- }
- return -1; // if key does not found, return -1
- } // end of binarySearch method
- }
Output: 6
No comments:
Post a Comment