Hacks
Hacks
public class BinarySearch {
private int search(int[] array, int group1, int group2, int selected ) {
// if group1 index is greater than group2 or group1 index is greater than largest index, stop running and return -1
if (group1 <= group2 && group1 < array.length-1) {
// obtain the middle index
int mid = group1+(group2-1)/2;
if (selected == array[mid]) {
// return index if selected is found
return mid;
} else if (selected < array[mid]) {
// update index
return search(array, group1, mid-1, selected);
} else if (selected > array[mid]) {
// update index and run search again
return search(array, mid+1, group2, selected);
}
}
return -1;
}
public int search(int[] array, int selected) {
return this.search(array, 0, array.length-1, selected);
}
public static void main() {
BinarySearch binary = new BinarySearch();
int[] array = {1, 3, 5, 7, 9, 23, 45, 67};
int index = binary.search(array, 45);
System.out.println(index);
}
}
BinarySearch.main();
public class UnsortedSearch {
void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
int[] L = new int[n1];
int[] R = new int[n2];
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];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
public void sort(int arr[], int l, int r) {
if (l < r) {
int mid = l + (r - l) / 2;
sort(arr, l, mid);
sort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
}
private int search(int[] array, int selected) {
this.sort(array,0,array.length-1);
BinarySearch search = new BinarySearch();
return search.search(array, selected);
}
public static void main() {
UnsortedSearch search = new UnsortedSearch();
int[] array = {5, 6, 3, 1, 8, 9, 4, 7, 2};
int index = search.search(array, 7);
System.out.println(index);
}
}
UnsortedSearch.main();