|
| 1 | +package algorithms.binary_search; |
| 2 | + |
| 3 | +import java.util.Scanner; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + private void run() { |
| 7 | + Scanner scanner = new Scanner(System.in); |
| 8 | + int elementsNumber = scanner.nextInt(); |
| 9 | + int[] array = new int[elementsNumber]; |
| 10 | + for (int i = 0; i < elementsNumber; i++) { |
| 11 | + array[i] = scanner.nextInt(); |
| 12 | + } |
| 13 | + int searchElementsNumber = scanner.nextInt(); |
| 14 | + int[] searchElements = new int[searchElementsNumber]; |
| 15 | + for (int i = 0; i < searchElementsNumber; i++) { |
| 16 | + searchElements[i] = scanner.nextInt(); |
| 17 | + } |
| 18 | + |
| 19 | + StringBuilder outputBuilder = new StringBuilder(); |
| 20 | + for (int i = 0; i < searchElementsNumber; i++) { |
| 21 | + int searchElementIndex = binarySearch(array, searchElements[i]); |
| 22 | + outputBuilder.append(String.format("%d ", searchElementIndex + 1)); |
| 23 | + } |
| 24 | + System.out.println(outputBuilder.toString()); |
| 25 | + } |
| 26 | + |
| 27 | + private int binarySearch(int[] array, int searchElement) { |
| 28 | + int left = 0; |
| 29 | + int right = array.length - 1; |
| 30 | + int currentIndex = (left + right) / 2; |
| 31 | + while (left < right) { |
| 32 | + if (searchElement == array[currentIndex]) { |
| 33 | + break; |
| 34 | + } |
| 35 | + if (searchElement < array[currentIndex]) { |
| 36 | + right = currentIndex - 1; |
| 37 | + } |
| 38 | + else { |
| 39 | + left = currentIndex + 1; |
| 40 | + } |
| 41 | + currentIndex = (left + right) / 2; |
| 42 | + } |
| 43 | + if (array[currentIndex] == searchElement) { |
| 44 | + return currentIndex; |
| 45 | + } |
| 46 | + return -2; |
| 47 | + } |
| 48 | + |
| 49 | + public static void main(String[] args) { |
| 50 | + new Main().run(); |
| 51 | + } |
| 52 | +} |
0 commit comments