Java BinarySearch

前端 未结 10 2119
忘了有多久
忘了有多久 2020-12-09 23:33

Can I get some help please? I have tried many methods to get this to work i got the array sorted and to print but after that my binary search function doesnt want to run and

相关标签:
10条回答
  • 2020-12-09 23:33
    /**
    HOPE YOU LIKE IT
    A.K.A Binary Search
    Take number array of 10 elements, input a number a check whether the number 
    is present:
    **/
    package array;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    import java.io.IOException;
    class BinaryS
    {
        public static void main(String args[]) throws IOException
        {       
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));      
        System.out.print("Enter a number: ");
        int n=Integer.parseInt(br.readLine());
        int a[]={10,20,30,40,50,60,70,80,90,100};
        int upper=a.length-1,lower=0,mid;
        boolean found=false;
        int pos=0;
        while(lower<=upper)
        {
            mid=(upper+lower)/2;
            if(n<a[mid])upper=mid-1;
            else if(n>a[mid])lower=mid+1;
            else
            {
                found=true;
                pos=mid;
                break;
            }
        }
        if(found)System.out.println(n+" found at index "+pos);
        else System.out.println(n+" not found in array");
    }
    }
    
    0 讨论(0)
  • 2020-12-09 23:40

    Here is a solution without heap. The same thing can be done in an array. If we need to find 'k' largest numbers, we take an array of size 'k' populated with first k items from the main data source. Now, keep on reading an item, and place it in the result array, if it has a place.

    public static void largestkNumbers() {
        int k = 4;    // find 4 largest numbers
        int[] arr = {4,90,7,10,-5,34,98,1,2};
        int[] result = new int[k];
    
        //initial formation of elems
        for (int i = 0; i < k; ++i) {
          result[i] = arr[i];
        }
        Arrays.sort(result);
    
        for ( int i = k; i < arr.length; ++i ) {
          int index = binarySearch(result, arr[i]);
          if (index > 0) {
            // insert arr[i] at result[index] and remove result[0]
            insertInBetweenArray(result, index, arr[i]);
          }
        }
      }
    
      public static void insertInBetweenArray(int[] arr, int index, int num) {
        // insert num at arr[index] and remove arr[0]
        for ( int i = 0 ; i < index; ++i ) {
          arr[i] = arr[i+1];
        }
        arr[index-1] = num;
      }
    
      public static int binarySearch(int[] arr, int num) {
    
        int lo = 0;
        int hi = arr.length - 1;
        int mid = -1;
    
        while( lo <= hi ) {
          mid = (lo+hi)/2;
          if ( arr[mid] > num ) {
            hi = mid-1;
          } else if ( arr[mid] < num ) {
            lo = mid+1;
          } else {
            return mid;
          }
        }
        return mid;
      }
    
    0 讨论(0)
  • 2020-12-09 23:41

    you are not actually comparing with the array values. in

    while (low <= high) {
          mid = (low + high) / 2;
          if (mid > key) {
              high = mid - 1;
          } else if (mid < key) {
              low = mid + 1;
          } else {
              return mid;
          }
    }
    

    Instead use this section

        while (low <= high) {
            mid = (low + high) / 2;
            if (a[mid] > key) {
                high = mid - 1;
            } else if (a[mid] < key) {
                low = mid + 1;
            } else {
                return mid;
            }
        }
    

    You were correct to find the indexes, but what you were doing is that you were just comparing index number with your key, which is obviously incorrect. When you write a[mid] you will actually compare your key with the number which is at index mid.

    Also the last line of code is giving compile error, it should be

    System.out.println("Found " + key + " at " + binarySearch(a, key));
    
    0 讨论(0)
  • 2020-12-09 23:51
    int BinSearch(int[] array, int size, int value)
    {
        if(size == 0) return -1;
        if(array[size-1] == value) return size-1;
        if(array[0] == value) return 0;
        if(size % 2 == 0) {
            if(array[size-1] == value) return size-1;
            BinSearch(array,size-1,value);
        }
        else
        {
            if(array[size/2] == value) return (size/2);
            else if(array[size/2] > value) return BinSearch(array, (size/2)+1, value);
        else if(array[size/2] < value) return (size/2)+BinSearch(array+size/2, size/2, value);
        }
    }
    

    or

    Binary Search in Array

    0 讨论(0)
  • 2020-12-09 23:55
    public static double binarySearch(double[] a, double key) {
    
        if (a.length == 0) {
          return -1;
        }
        int low = 0;
        int high = a.length-1;
    
        while(low <= high) {
          int middle = (low+high) /2; 
          if (b> a[middle]){
            low = middle +1;
          } else if (b< a[middle]){
            high = middle -1;
          } else { // The element has been found
            return a[middle]; 
          }
        }
        return -1;
      }
    
    0 讨论(0)
  • 2020-12-09 23:55
    int binarySearch(int list[], int lowIndex, int highIndex, int find)
        {
            if (highIndex>=lowIndex)
            {
                int mid = lowIndex + (highIndex - lowIndex)/2;
    
                // If the element is present at the
                // middle itself
                if (list[mid] == find)
                    return mid;
    
                // If element is smaller than mid, then
                // it can only be present in left subarray
                if (list[mid] > find)
                    return binarySearch(list, lowIndex, mid-1, find);
    
                // Else the element can only be present
                // in right subarray
                return binarySearch(list, mid+1, highIndex, find);
            }
    
            // We reach here when element is not present
            //  in array
            return -1;
        }
    
    0 讨论(0)
提交回复
热议问题