- Recursive Method in Java
- Recursive Method in Java
I have implemented the Binary Search algorithm in both iterative and recursive ways. This post explains the concept of Binary Search with easy-to-understand steps and working Java code examples. The goal is to help beginners learn how Binary Search works and how to implement it practically in Java.
Iterative Method in Java
public class BinarySearchIterative { public static int binarySearch(int[] arr, int key) { int start = 0; int end = arr.length - 1; while (start <= end) { int mid = start + (end - start) / 2; if (arr[mid] == key) { return mid; } else if (arr[mid] < key) { start = mid + 1; } else { end = mid - 1; } } return -1; } public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; int target = 30; int result = binarySearch(numbers, target); if (result != -1) { System.out.println("Element found at index: " + result); } else { System.out.println("Element not found."); } } }OUTPUT
Element found at index: 2
Recursive Method in Java
public class BinarySearchRecursive { public static int binarySearch(int[] arr, int start, int end, int key) { if (start > end) { return -1; } int mid = start + (end - start) / 2; if (arr[mid] == key) { return mid; } else if (arr[mid] < key) { return binarySearch(arr, mid + 1, end, key); } else { return binarySearch(arr, start, mid - 1, key); } } public static void main(String[] args) { int[] numbers = {5, 15, 25, 35, 45}; int target = 25; int result = binarySearch(numbers, 0, numbers.length - 1, target); if (result != -1) { System.out.println("Element found at index: " + result); } else { System.out.println("Element not found."); } } }OUTPUT
Element found at index: 2