Binary Search Hacks
public class BinarySearch {
public int BinarySearch(int[] nums, int target, int start, int end) {
// 1. Base case
if (start > end) {
return -1;
}
// set mid
int mid = start + (end - start) / 2;
// check if mid is target
if (nums[mid] == target) {
return mid;
} else if (nums[mid] > target) { // check if mid is greater than target
return BinarySearch(nums, target, start, mid - 1); // recursive call with new end as mid
} else {
return BinarySearch(nums, target, mid + 1, end); // recursive call with new start as mid
}
}
// starter method for binary search
public int BinarySearch(int[] nums, int target) {
return BinarySearch(nums, target, 0, nums.length - 1);
}
public static void main(String[] args) {
BinarySearch bs = new BinarySearch();
int[] nums = { 1, 3, 5, 7, 9, 23, 45, 67 };
int target = 45;
int index = bs.BinarySearch(nums, target);
System.out.println(index);
}
}
BinarySearch.main(null);
public class MergeSortAndBinarySearch {
// uses comparable as a generic type, as long as the type implements comparable
// any primitive will work as well as any object that implements comparable
static void sort(Comparable arr[], int l, int r)
{
if (l < r) {
// COMMENT A
int m = l + (r - l) / 2;
// COMMENT B
sort(arr, l, m);
sort(arr, m + 1, r);
// COMMENT C
merge(arr, l, m, r);
}
}
static void merge(Comparable arr[], int l, int m, int r)
{
// Find the sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
Comparable[] L = new Comparable[n1];
Comparable[] R = new Comparable[n2];
/* Copy data to temp arrays */
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarray array
int k = l;
while (i < n1 && j < n2) {
if (L[i].compareTo(R[j]) < 0) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
public static void main(String[] args) {
// testing
Integer[] arr = { 5, 6, 3, 1, 8, 9, 4, 7, 2};
int n = arr.length;
sort(arr, 0, n - 1);
System.out.println(Arrays.toString(arr));
int[] primSorted = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
primSorted[i] = arr[i];
}
BinarySearch bs = new BinarySearch();
int index = bs.BinarySearch(primSorted, 7);
System.out.println(index);
}
}
MergeSortAndBinarySearch.main(null);