Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

Java Binary Search Algorithm

// Java Binary Search Algorithm
// ----------------------------

/* 
   Time Complexity
     Best Time Complexity:O(1)
	 Average Time Complexity:O(log n)
	 Worst Time Complexity:O(log n)
     
   Space Complexity
     No auxiliary space is required in Linear Search implementation.
	 Hence space complexity is:O(1)
*/

public class BinarySearch {

    // Searching using Recursive approach
    public static int Search(int arr[], int value, int start, int end) {
        int center = (start + end) / 2;

        if (start <= end) {
            if (value == center) {
                return center;
            }

            if (value < center) {
                return Search(arr, value, start, center - 1);
            }

            if (value > center) {
                return Search(arr, value, center + 1, end);
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        int arr[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

        int Index = Search(arr, 9, 0, arr.length);
        if (Index == -1) {
            System.out.println("Value Not Found");
        } else {
            System.out.println("Value found at Index: " + Index);
        }
    }
}
Source by teamtreehouse.com #
 
PREVIOUS NEXT
Tagged: #Java #Binary #Search #Algorithm
ADD COMMENT
Topic
Name
1+1 =