|
1 | 1 | package search;
|
2 | 2 |
|
| 3 | +/**Binary search works only for sorted list of items.*/ |
3 | 4 | public class BinarySearch {
|
4 | 5 |
|
| 6 | + static int search(double[] numbers, double value){ |
| 7 | + boolean found = false; |
| 8 | + int round = 0; |
| 9 | + int start = 0; |
| 10 | + int end = numbers.length - 1; |
| 11 | + int middle = 0; |
| 12 | + |
| 13 | + while(!found){ |
| 14 | + middle = (end + start) / 2; |
| 15 | + showStep(numbers, start, end, middle, round); |
| 16 | + |
| 17 | + if(numbers[middle] == value) |
| 18 | + found = true; |
| 19 | + else if(numbers[middle] < value) |
| 20 | + start = middle + 1; |
| 21 | + else if(numbers[middle] > value) |
| 22 | + end = middle - 1; |
| 23 | + |
| 24 | + round++; |
| 25 | + } |
| 26 | + |
| 27 | + return middle; |
| 28 | + } |
| 29 | + static void showStep(double[] numbers, int start, int end, int mid, int round) { |
| 30 | + if(round == 0) |
| 31 | + System.out.println("BINARY SEARCH ALGORITHM"); |
| 32 | + else |
| 33 | + System.out.println("round" + round + "=> search interval=[" + start + ", " + end+"] midInd= "+ mid +" value = " + numbers[mid]); |
| 34 | + System.out.println("------------------------------------------------------------------------------------------------------------------"); |
| 35 | + } |
| 36 | + |
| 37 | + public static void main(String[] args) { |
| 38 | + |
| 39 | + double numbers[] = {-11, 0, 6, 10, 14, 20, 50, 73, 92, 100, 255}; |
| 40 | + |
| 41 | + /**print the sorted array*/ |
| 42 | + System.out.print("Sorted List:{ "); |
| 43 | + for (int i = 0; i < numbers.length - 1; i++) |
| 44 | + System.out.print(numbers[i] + " "); |
| 45 | + System.out.println(numbers[numbers.length - 1]+" }"); |
| 46 | + /**print subscripts*/ |
| 47 | + System.out.print("indexes: "); |
| 48 | + for (int i = 0; i < numbers.length - 1; i++) |
| 49 | + System.out.print(i + " "); |
| 50 | + System.out.println(numbers.length - 1); |
| 51 | + |
| 52 | + /**Execute the search algorithm*/ |
| 53 | + search(numbers, 0); |
| 54 | + |
| 55 | + } |
| 56 | + |
5 | 57 | }
|
0 commit comments