Wednesday, June 20, 2018

How do you do binary search in java?

Problem statement: How will you do for binary search in java?
  1. public class BinarySearchExe {
  2. public static void main(String[] args) {
  3. int a[] = { 2, 4, 5, 6, 7, 9, 10 };
  4. int idx = binarySearch(a, 10);
  5. System.out.println(idx);
  6. } // end of main
  7. static int binarySearch(int a[], int key) {
  8. int start = 0, end = a.length - 1;
  9. while (start <= end) {
  10. int mid = (start + end) / 2;
  11. if (key == a[mid]) {
  12. return mid;
  13. } else if (key > a[mid]) {
  14. start = mid + 1;
  15. } else {
  16. end = mid - 1;
  17. }
  18. }
  19. return -1; // if key does not found, return -1
  20. } // end of binarySearch method
  21. }
Output: 6

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...