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

Java Binary Search

/*
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 :: csv compare java 
Java :: android press back 2 times to exit 
Java :: expression régulière téléphone java 
Java :: retrofit post body 
Java :: Read json url in android - NAYCode.com 
Java :: get width and height of screen libgdx 
Java :: final method and abstract method 
Java :: android snackbar message is behind back button 
Java :: kotlin edittext default value 
Java :: java background color 
Java :: java list of lists 
Java :: Java code to launch shell script with arguments 
Java :: initialize empty dictionary java 
Java :: merge without extra space 
Java :: greatest of three in java 
Java :: java break string at comma 
Java :: how to use iterator in java 
Java :: java arraylist initialize with 0 
Java :: Java Access superclass attribute 
Java :: Java Access Array Elements 
Java :: list interface java 
Java :: java log4j example 
Java :: how to check size of arrayin java 
Java :: format specifier in java 
Java :: how to remove leading space in java 
Java :: what is return method 
Java :: authentication in spring boot 
Java :: calling a void method java 
Java :: How do you make bedrock full screen in Minecraft? 
Java :: two dimensional arraylist in java 
ADD CONTENT
Topic
Content
Source link
Name
7+4 =