Thursday, May 31, 2018

Binary search program in java.

Problem statement: What & how do you do binary search ?
  1. A simple approach is to do linear search.
  2. The time complexity of this approach's algorithm is O(n). 
  3. Another approach to perform the same task is using Binary SearchIn case of binary search, array elements must be sorted in ASCENDING order, not in DESCENDING order
  4. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n).
  5. Binary search is faster than linear search.
  • Algorithm:
  1. Search a sorted array by repeatedly dividing the search interval in half. 
  2. Begin with an interval covering the whole array. 
  3. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. 
  4. Otherwise narrow it to the upper half. 
  5. Repeatedly check until the value is found or the interval is empty.
N.B. - In case of binary search, array elements must be in ascending order. If you have UNSORTED array, you can sort the array using Arrays.sort(arr) method.

METHOD-I:

  1. public class BinarySearchExe {
  2. public static void main(String args[]) {
  3. int arr[] = { 10, 20, 30, 40, 50 };
  4. binarySearchss(arr, 30);
  5. }
  6. public static void binarySearchss(int a[], int key) {
  7. int start = 0, end = a.length - 1;
  8. int mid = (start + end) / 2;
  9. while (start <= end) {
  10. if (key == a[mid]) {
  11. System.out.println("key at index: " + mid);
  12. break;
  13. } else if (key > a[mid]) {
  14. start = mid + 1;
  15. } else {
  16. end = mid - 1;
  17. }
  18. mid = (start + end) / 2;
  19. }
  20. if (start > end) {
  21. System.out.println("key not found!");
  22. }
  23. }
  24. }
Output: 
key at index: 2
Time complexity: O(log n)

METHOD-II:
  1. public class BinarySearchExe {
  2. public static void main(String[] args) {
  3. int a[] = { 10, 20, 30, 40, 50 };
  4. int idx = binarySearch(a, 30);
  5. System.out.println("key at index: " + idx);
  6. }
  7. public 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. }
  14. if (key < a[mid]) {
  15. end = mid - 1;
  16. } else {
  17. start = mid + 1;
  18. }
  19. }
  20. return -1;
  21. }
  22. }
Output: 
key at index: 2
Time complexity: O(log n)

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...