Binary Search in Java


 

Binary Search in Java

In this section, we are going to search an element from an array using Binary Search. The advantage of a binary search over a linear search is astounding for large numbers.

In this section, we are going to search an element from an array using Binary Search. The advantage of a binary search over a linear search is astounding for large numbers.

Binary Search in Java

In this section, we are going to search an element from an array using Binary Search. The advantage of a binary search over a linear search is astounding for large numbers. It can be done either recursively or iteratively. In the given code, we have allowed the user to enter the numbers to be stored into the array.Then we start the search from the middle element of the array. If the middle element is equal to the searched value, the algorithm stops otherwise we have two cases:

1)If searched value is less than the middle element. In this case, again get the middle element of the first half of the specified array.
2)If searched value is greater, than the middle element. In this case, again get the middle element of the second half of the specified array.
This will continue until we get the searched element.

Here is the code:

import java.util.*;

public class BinarySearch {
	public static void main(String[] args) {
		int[] intArray = new int[10];
		int searchValue = 0, index;
		System.out.println("Enter 10 numbers");
		Scanner input = new Scanner(System.in);
		for (int i = 0; i < intArray.length; i++) {
			intArray[i] = input.nextInt();
		}
		System.out.print("Enter a number to search for: ");
		searchValue = input.nextInt();
		index = binarySearch(intArray, searchValue);
		if (index != -1) {
			System.out.println("Found at index: " + index);
		} else {
			System.out.println("Not Found");
		}
	}

	static int binarySearch(int[] search, int find) {
		int start, end, midPt;
		start = 0;
		end = search.length - 1;
		while (start <= end) {
			midPt = (start + end) / 2;
			if (search[midPt] == find) {
				return midPt;
			} else if (search[midPt] < find) {
				start = midPt + 1;
			} else {
				end = midPt - 1;
			}
		}
		return -1;
	}
}

Output

Enter 10 numbers:
1
2
3
4
5
6
7
8
9
10
Enter a number to search for:5
Found at index: 4

Ads