Advertisement
Guest User

Binary Search

a guest
Mar 27th, 2013
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * BinarySearch.java
  3.  *
  4.  * My first attempt; crude, but it works.
  5.  */
  6.  
  7. import java.util.Scanner;
  8.  
  9. public class BinarySearch {
  10.     public static void main(String[] args) {
  11.         Scanner sin = new Scanner(System.in);
  12.         int[] array = getInts(sin);
  13.         int n = 0, pos = 0, low = 0, high = (array.length - 1);
  14.        
  15.         System.out.print("Enter a number to find: ");
  16.         n = sin.nextInt();
  17.        
  18.         if (n < array[low] || n > array[high])
  19.             System.out.println("Impossible to find.");
  20.         else if (n == array[low] || n == array[high])
  21.             System.out.println("array[" + pos + "]=\t" + array[pos]);
  22.         else {
  23.             while (array[pos] != n) {
  24.                 if (n >= ((low + high) / 2)) low = (low + high) / 2;
  25.                 else if (n <= ((low + high) / 2)) high = (low + high) / 2;
  26.                 else break;
  27.                 pos = low;
  28.             }
  29.            
  30.             System.out.println("array[" + pos + "]=\t" + array[pos]);
  31.         }      
  32.     }
  33.  
  34.     public static int[] getInts() {
  35.         int[] array = new int[1000];
  36.        
  37.         for (int i = 0; i < (array.length - 1); i++)
  38.             array[i] = i;
  39.        
  40.         return array;
  41.     }
  42. }
  43.  
  44. // scottyeatscode.blogspot.com
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement