Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

binary search java

import java.util.*;
public class array
{
    static Scanner sc=new Scanner(System.in);
    public static void main(String[] args)
    {
        System.out.println("Enter the number of elements in the array:");
        int x=sc.nextInt();
        int arr[]=new int[x];
        System.out.println("Enter the sorted elements in the array:");
        for(int i=0; i<arr.length; i++)
        {
            arr[i]=sc.nextInt();
        }
        System.out.println("Enter the element to be searched for in the array:");
        int y=sc.nextInt();
        int max=arr.length-1;
        int min=0;
        int mid;
        while(max>=min)
        {
            mid=(min+max)/2;
            if(y==arr[mid])
            {
                System.out.println("The requested element is at index "+mid);
                break;
            }
            else if(y>arr[mid])
                min=mid+1;
            else if(y<arr[mid])
                max=mid-1;
            if(min>max)
                System.out.println("Requested element is not in the array.");
        }
    }
}
Comment

binary search java

public int runBinarySearchRecursively(
  int[] sortedArray, int key, int low, int high) {
    int middle = (low + high) / 2;
        
    if (high < low) {
        return -1;
    }

    if (key == sortedArray[middle]) {
        return middle;
    } else if (key < sortedArray[middle]) {
        return runBinarySearchRecursively(
          sortedArray, key, low, middle - 1);
    } else {
        return runBinarySearchRecursively(
          sortedArray, key, middle + 1, high);
    }
}
Comment

binary search java

/*
Java Implementation of Binary Search Algorithm.
- Assuming the Array is Sorted (Ascending Order)
- returns the Index, if Element found.
- -1, if not found.
*/
public class BinarySearch {

    int binarysearch(int[] array, int element) {
        int a_pointer = 0;
        int b_pointer = array.length -1;
      	if (array[a_pointer] == element) return a_pointer;
        if (array[b_pointer] == element) return b_pointer;

        while(a_pointer <= b_pointer){
            int midpoint = a_pointer + (b_pointer - a_pointer) / 2;
          	if (array[midpoint] == element) return midpoint;
          
          	// ignoring the left half, if this is True.
            if (array[midpoint] < element) a_pointer = midpoint + 1;
          
          	// ignoring the right half, if this is True.
            else if (array[midpoint] > element) b_pointer = midpoint - 1;
        }
        return -1;	// Element not Found
    }
    public static void main(String[] args) {
        int[] list = {1, 2, 3, 4, 7, 9, 11, 12, 15, 19, 23, 36, 54, 87};
        System.out.println(binarysearch(list, 19));
    }
}
Comment

java binary search

import java.util.*;

public class Search {
    static int indexOfItem(List<String> list, String target) {
        int first = 0;
        int last = list.size() - 1;
        while (first <= last) {
            int midpoint = (first + last) / 2;
            int comparisonResult = list.get(midpoint).compareTo(target);
            if (comparisonResult == 0) {
                return midpoint;
            } else if (comparisonResult < 0) {
                first = midpoint + 1;
            } else {
                last = midpoint - 1;
            }
        }
        // We have to return an integer, so return an "impossible"
        // index to indicate value was not found.
        return -1;
    }

    public static void main(String[] args) {
        // Note that the list is sorted this time!
        ArrayList<String> list = new ArrayList<String>(
            Arrays.asList("Elida Sleight", "Francina Vigneault", "Lucie Hansman", "Nancie Rubalcaba"));
        System.out.println(indexOfItem(list, "Lucie Hansman"));
    }
}
Comment

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");
        }

    }
}
Comment

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);
        }
    }
}
Comment

Binary Search Java

// Java implementation of recursive Binary Search
class BinarySearch {
    // Returns index of x if it is present in arr[l..
    // r], else return -1
    int binarySearch(int arr[], int l, int r, int x)
    {
        if (r >= l) {
            int mid = l + (r - l) / 2;
  
            // If the element is present at the
            // middle itself
            if (arr[mid] == x)
                return mid;
  
            // If element is smaller than mid, then
            // it can only be present in left subarray
            if (arr[mid] > x)
                return binarySearch(arr, l, mid - 1, x);
  
            // Else the element can only be present
            // in right subarray
            return binarySearch(arr, mid + 1, r, x);
        }
  
        // We reach here when element is not present
        // in array
        return -1;
    }
  
    // Driver method to test above
    public static void main(String args[])
    {
        BinarySearch ob = new BinarySearch();
        int arr[] = { 2, 3, 4, 10, 40 };
        int n = arr.length;
        int x = 10;
        int result = ob.binarySearch(arr, 0, n - 1, x);
        if (result == -1)
            System.out.println("Element not present");
        else
            System.out.println("Element found at index "
                               + result);
    }
}
/* This code is contributed by Rajat Mishra */
Comment

Binary Search java

package com.community.java;
/**
 * 
 * @author Akira
 */
public class ContohBinarySearch {
    private final int [] data = {5, 9, 12, 15, 17, 23, 27, 38, 42, 54, 64, 78, 90};
    
    private void tampilData(){
        for (int i : data) {
            System.out.print(i+" ");
        }
        System.out.println();
    }
    
    public String pencarianBinary(int key) {
        int bawah = 0;
        int atas = data.length - 1;

        while (atas >= bawah) {
            int tengah = (bawah + atas) / 2;
            if (key < data[tengah]){
                atas = tengah - 1;
            } else if (key == data[tengah]){
                return "Nomor "+key+" Berada Pada Urutan Ke - "+(tengah+1);
            }else{
                bawah = tengah + 1;
            }
        }
        return "Data Tidak Ditemukan";
    }
 
    public static void main(String args []){
        ContohBinarySearch obj = new ContohBinarySearch();
        obj.tampilData();
        System.out.println(obj.pencarianBinary(8));
    }

}
Comment

binary search program in java

public class Main{ public static void binarySearch(int arr[], int a, int b, int key){ int mid = (a + b)/2; while( a <= b ){ if ( arr[mid] < key ){ a = mid + 1; }else if ( arr[mid] == key ){ System.out.println("number is here " + mid); break; }else{ b = mid - 1; } mid = (a + b)/2; } if ( a > b ){ System.out.println("number not here"); } } public static void main(String args[]){ int arr[] = {10,20,30,40,50}; int key = 30; int b=arr.length-1; binarySearch(arr,0,b,key); } } 
Comment

PREVIOUS NEXT
Code Example
Java :: java and or precedence 
Java :: JAVA Multi-line Comment 
Java :: json java 
Java :: access array elements java 
Java :: look and feel java 
Java :: Syntax of Creating Java Map Objects 
Java :: java to c# converter 
Java :: @restcontroller 
Java :: get node inside node in of xml using java 
Java :: get string size on screen 
Java :: nth fibonacci number java using for loop 
Java :: Example of a Do..While Loop 
Java :: Java Create a BufferedReader 
Java :: default constructor 
Java :: new date api in java 8 
Java :: Error: Could not find or load main class Hello Caused by: java.lang.ClassNotFoundException: Hello studio visual code 
Java :: valid parentheses leetcode solution java 
Java :: try catch in java 
Java :: super 
Java :: minecraft addlayer(u) in the type rendererlivingentity<t is not applicable for the arguments 
Java :: How to send saved CSV file via email 
Java :: spring aop xml definition 
Java :: empty map entry java 
Java :: rotate vector 3d java 
Java :: programme javascrip mineur et majaur 
Java :: unirest javafx 
Java :: java returning an comparable array of inorder traversal of binary tree 
Java :: Get Subarray from Array 
Java :: create object of hashMap with integer key and String value 
Java :: EXPECTTIONS JAVA 
ADD CONTENT
Topic
Content
Source link
Name
3+6 =