Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * BinarySearch.java
- *
- * My first attempt; crude, but it works.
- */
- import java.util.Scanner;
- public class BinarySearch {
- public static void main(String[] args) {
- Scanner sin = new Scanner(System.in);
- int[] array = getInts(sin);
- int n = 0, pos = 0, low = 0, high = (array.length - 1);
- System.out.print("Enter a number to find: ");
- n = sin.nextInt();
- if (n < array[low] || n > array[high])
- System.out.println("Impossible to find.");
- else if (n == array[low] || n == array[high])
- System.out.println("array[" + pos + "]=\t" + array[pos]);
- else {
- while (array[pos] != n) {
- if (n >= ((low + high) / 2)) low = (low + high) / 2;
- else if (n <= ((low + high) / 2)) high = (low + high) / 2;
- else break;
- pos = low;
- }
- System.out.println("array[" + pos + "]=\t" + array[pos]);
- }
- }
- public static int[] getInts() {
- int[] array = new int[1000];
- for (int i = 0; i < (array.length - 1); i++)
- array[i] = i;
- return array;
- }
- }
- // scottyeatscode.blogspot.com
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement