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

Binary Search Program

binary search program

Uploaded by

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

Binary Search Program

binary search program

Uploaded by

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

Binary search program

Aim:
The aim of this program is to create a simple Java application that allows a user
to search for a specific number within a sorted array of integers using the binary
search technique.
Algorithm:
Step 1: Start the program
Step 2: Create an array of the specified size.
Step 3: Input the array elements from the user in sorted order and Store
these elements in the array.
Step 4: Prompt the user to enter the number they want to search for in the
array.
Step 5: Set two pointers, start at 0 and end at the last index of the array.
Step 6: Binary Search Process:
o While the start pointer is less than or equal to the end pointer:
 Calculate the middle index mid.
 If the middle element equals the target, return the mid index
(indicating the target is found).
 If the middle element is less than the target, move the start
pointer to mid + 1 (search the right half).
 If the middle element is greater than the target, move the end
pointer to mid - 1 (search the left half).
Step 7: If the target is found, output the index where it is located.
Step 8: If the target is not found after the loop, output that the number is
not in the array.
Step 9: Save and execute the program
Step 10: Stop the execution.
Program
import java.util.Scanner;
public class EasyBinarySearch {
// Method to search for a number
public static int search(int[] arr, int target) {
int start = 0, end = arr.length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] == target) {
return mid; // Target found
}
if (arr[mid] < target) {
start = mid + 1; // Search right half
} else {
end = mid - 1; // Search left half
}
}
return -1; // Target not found
}
// Main method to interact with the user
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Get array size
System.out.print("Enter number of elements: ");
int size = sc.nextInt();
int[] arr = new int[size];
// Get array elements
System.out.println("Enter sorted elements:");
for (int i = 0; i < size; i++) {
arr[i] = sc.nextInt();
}
// Get number to find
System.out.print("Enter number to find: ");
int target = sc.nextInt();
// Perform the search
int result = search(arr, target);
// Display result
if (result == -1) {
System.out.println("Number not found.");
} else {
System.out.println("Number found at index: " + result);
}
sc.close();
}
}

You might also like