Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

binary search algorithm in java

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.SortingAlgorithm;

import java.util.Scanner;

public class BinarySearch {
    public BinarySearch() {
    }
    
  // write a function that performs your binary search.
    static int binarySearch(int[] arr, int target, int n) {
      // declare your right and left pointers.
        int lp = 0; 
        int rp = n - 1;
      
  // write loop that compares the left & right pointers and returns the mid point
        while(lp <= rp) {
            int mid = (lp + rp) / 2;
            if (target == arr[mid]) {
                return mid;
            }
// write an if statement to check for target element at mid point
            if (target < arr[mid]) {
                rp = mid - 1;
            } else {
                lp = mid + 1;
            }
        }

        return -1;
    }
  
// driver method to test the above
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int target = false;
        System.out.print("Enter the number of elements tou on the array list! :");
        int n = scanner.nextInt();
        int[] arr = new int[n];
        System.out.println("enter " + n + " Elements");

        for(int i = 0; i < n; ++i) {
            arr[i] = scanner.nextInt();
        }

        System.out.println("Enter target value: ");
        int target = scanner.nextInt();
        int index = binarySearch(arr, target, n);
        if (index != -1) {
            System.out.println("Element is at index: " + index);
        } else {
            System.out.format("Element not found");
        }

    }
}
Source by teamtreehouse.com #
 
PREVIOUS NEXT
Tagged: #binary #search #algorithm #java
ADD COMMENT
Topic
Name
9+2 =