0% found this document useful (0 votes)
5 views

Binary Search

The document contains a Java implementation of the binary search algorithm, which efficiently finds the index of a specified key in a sorted array. It defines a recursive method 'binarySearch' that checks the middle element and narrows down the search range accordingly. The main method demonstrates the usage of this algorithm with a sample array and key.

Uploaded by

csestaff24
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Binary Search

The document contains a Java implementation of the binary search algorithm, which efficiently finds the index of a specified key in a sorted array. It defines a recursive method 'binarySearch' that checks the middle element and narrows down the search range accordingly. The main method demonstrates the usage of this algorithm with a sample array and key.

Uploaded by

csestaff24
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

BinarySearch

class BinarySearch

public static int binarySearch(int arr[], int first, int last, int key)

if (last >= first) {

int mid = (first + last) / 2;

if (arr[mid] == key) {

return mid;

} else if (arr[mid] > key) {

return binarySearch(arr, first, mid - 1, key);

} else {

return binarySearch(arr, mid + 1, last, key);

return -1;

public static void main(String args[]) {

int arr[] = {10, 20, 30, 40, 50};

int key = 30;

int last = arr.length - 1;

int result = binarySearch(arr, 0, last, key);

if (result == -1) {

System.out.println("Element is not found!");

else
{

System.out.println("Element is found at index: " + result);

You might also like