Binary Search Java Code

 Pseudo Code:

start =0, end = n-1

While(start<=end) 

find mid  {mid=(start+end)/2}

compare mid and key

mid==key {found}

mid>key {Left} end=mid-1

mid<key {right} start=mid+1

if not found: return -1

public class BinarySearch {
    public static int SearchBinary(int num[], int key) {
        int start = 0, end = num.length - 1;

        while (start <= end) {
            int mid = (start + end) / 2;

            // comparison
            if (num[mid] == key) {
                return mid;
            }
            if (num[mid] > key) {
                end = mid - 1; // left
            } else {
                start = mid + 1; // right : mid < key
            }

        }
        return -1;
    }

    public static void main(String[] args) {
        int numbers[] = { 2, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 80, 24, 30 };
        System.out.println(SearchBinary(numbers, 14));
        System.out.println("Hello World");
    }
}

No comments:

Post a Comment

Max Sub Array Sum: Kadane's Algorithm

Code of: Max Sub Array Sum: Kadane's Algorithm. public class MaxSubArraySumKadanesALgorithm {     public static void Kadane ( int ...