View difference between Paste ID: cWdgMdkA and 7TmWS4b4
SHOW: | | - or go back to the newest paste.
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);
12+
		int[] array = getInts();
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
					
28
				pos = low;
29
			}
30
			
31-
		}		
31+
32
		}
33
	}
34
	
35
	public static int[] getInts() {
36
		int[] array = new int[1000];
37-
		for (int i = 0; i < (array.length - 1); i++)
37+
38
		for (int i = 0; i < 1000; i++)
39
			array[i] = i;
40
		
41
		return array;
42
	}
43
}
44
45
// scottyeatscode.blogspot.com