Created
May 29, 2018 07:00
-
-
Save Asutosh11/30784bc7119b03768cd0e28ba430c4a7 to your computer and use it in GitHub Desktop.
Algorithms in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1. BINARY SEARCH | |
public class BinarySearch { | |
int number_to_find; | |
public BinarySearch(Integer[] arr, int number_to_find){ | |
this.number_to_find = number_to_find; | |
int start_pos = 0; | |
int last_pos = arr.length-1; | |
BinarySearch(arr, start_pos, last_pos); | |
} | |
public void BinarySearch(Integer[] arr, int start_pos, int last_pos){ | |
int mid_pos = start_pos + ((last_pos-start_pos)/2); | |
if(number_to_find > arr[arr.length-1] || number_to_find < arr[0]){ | |
System.out.print("number_to_find not found in the array"); | |
} | |
else if(number_to_find < arr[mid_pos]){ | |
last_pos = mid_pos-1; | |
BinarySearch(arr, start_pos, last_pos); | |
} | |
else if(number_to_find > arr[mid_pos]){ | |
start_pos = mid_pos+1; | |
BinarySearch(arr, start_pos, last_pos); | |
} | |
else if (number_to_find == arr[mid_pos]){ | |
System.out.print("number_to_find found at " + mid_pos); | |
} | |
} | |
} | |
------------------------------------------------------------------------------------------------------------------------ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment