简体   繁体   中英

how to binary search one specific element in an array?

i have a binary search algorithm set up but i didn't know how to make it work like what where im suppose to tell it to look for an element and show if it is found or not any tip would help thank you

public static int search(int arr[], int x)
{ 
    int startIndex = 0 ; 
    int endIndex = arr.length-1;
    while ( startIndex <=endIndex){
    int midpoint = (startIndex + endIndex )/2;
    if(arr[midpoint]==x)
        return midpoint;
    else if(arr[midpoint]<x)
        startIndex=midpoint+1;
    else
        endIndex = midpoint = -1;
    }
    return -1;
}
 
//here i want to make it search for 6 

    public static void main (String [] args ){
     search v = new search();
     int [] test = {1,99,6,32,4,6,33,90};
     for (int element: test) {
    System.out.println("the elements of array: "+ element);
    int x = 6;
    int result=v.binarySearch();
     }

Binary Search works as, Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.

    int[] test = {1, 99, 6, 32, 4, 6, 33, 90};
    int num = 6;
    Arrays.sort(test);
    System.out.println(binarySearch(test, num, 0, test.length));

logic for the binary search is given below as,

public int binarySearch(int arr[], int num, int min, int max) {
    if (min > max) {
      return -1;
    }
    int mid = min + (max - min) / 2;
    if (arr[mid] == num) {
      return mid;
    } else if (arr[mid] < num) {
      return binarySearch(arr, num, mid + 1, max);
    }
    return binarySearch(arr, num, min, mid - 1);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM