Questions

  • 1 C
  • 2 C
  • 3 B
  • 4 C
  • 5 D

Hack #1

public class BinarySearch {
    private int search(int[] array, int left, int right, int target ) {
        // if left index is greater than right or left index is greater than largest index, stop running and return -1
        if (left <= right && left < array.length-1) {
            // get mid index
            int mid = left+(right-1)/2;
            if (target == array[mid]) {
                // return index if target is found
                return mid;
            } else if (target < array[mid]) {
                // update index to the left and run search again 
                return search(array, left, mid-1, target);
            } else if (target > array[mid]) {
                // update index to the right and run search again
                return search(array, mid+1, right, target);
            }
        }
        return -1;
    }
    public int search(int[] array, int target) {
        return this.search(array, 0, array.length-1, target);
    }
    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();
6

Hack #2

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 target) {
        this.sort(array,0,array.length-1);
        BinarySearch search = new BinarySearch();
        return search.search(array, target);
    }
    
    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();
6