10.1 Binary Search

Binary Search Tree Optimize - Recussive

static boolean binarySearchRecussive(int[] x, int start, int end, int n) {
    if (end < start)
        return false;
    int mid = (start + end) / 2;

    if (x[mid] == n) {
        return true;
    } else {
        if (x[mid] < n) {
            return binarySearchRecussive(x, mid + 1, end, n); // right tree
        } else {
            return binarySearchRecussive(x, start, mid - 1, n); // left tree
        }
    }
}

Binary Search Tree Optimize - Non Recussive

static int binarySearchNonRecusive(int[] a, int x) {
    int low = 0;
    int high = a.length - 1;
    int mid;

    while (low <= high) {
        System.out.print("c");
        mid = (low + high) / 2;

        if (a[mid] < x) {
            low = mid + 1;
        } else if (a[mid] > x) {
            high = mid - 1;
        } else {
            return mid;
        }
    }
    return -1; // Error
}

Main Method

public static void main(String[] args) {
    HashSet<Integer> temp = new HashSet<Integer>();
    int[] list1 = new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
    int[] list2 = new int[] { 1, 3, 4, 5, 7, 8, 10, 13, 14 };
    int[] list3 = new int[] { 4, 10, 12, 15, 18, 22, 24, 25, 31, 35, 44,
                50, 66, 70, 90 };

    System.out.println(" binarySearch Recussive List 1 : " + binarySearchRecussive(list1, 0, list1.length - 1, 80));
    System.out.println(" binarySearch Recussive List 2 : " +binarySearchRecussive(list2, 0, list2.length - 1, 14));
    System.out.println(" binarySearch Recussive List 3 : " +binarySearchRecussive(list3, 0, list3.length - 1, 44));

    System.out.println("\nbinarySearch Non Recussive List 1 : " + binarySearchNonRecusive(list1,  900));
    System.out.println("\nbinarySearch Non Recussive List 1 : " + binarySearchNonRecusive(list1,  80));
}

located@ package bst.BinarySearch.java

results matching ""

    No results matching ""