7.
IMPLEMENTATION OF LINEAR AND BINARY SEARCH
AIM:
To write a Java program to implement Linear Search and Binary
Search techniques to search an element in an array using user
input.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the number of elements.
Step 3: Create an array of given size.
Step 4: Read the elements into the array.
Step 5: Read the element to be searched.
Step 6: Display the search options and read the user’s choice.
Step 7: If Linear Search is chosen, compare each element with the key
until the element is found and display its position.
Step 8: If Binary Search is chosen, set low = 0 and high = n-1, find the
middle element and compare with the key repeatedly until the element
is found and display its position.
Step 9: Stop the program.
PROGRAM:
import [Link];
public class SearchProgram {
public static void main(String[ ] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of elements: ");
int n = [Link]();
int arr[ ] = new int[n];
[Link]("Enter elements:");
for(int i = 0; i < n; i++) {
arr[i] = [Link]();
[Link]("Enter element to search: ");
int key = [Link]();
[Link]("1. Linear Search");
[Link]("2. Binary Search");
[Link]("Choose method: ");
int choice = [Link]();
switch(choice) {
case 1:
boolean found1 = false;
for(int i = 0; i < n; i++) {
if(arr[i] == key) {
[Link]("Element found at position: " + (i + 1));
found1 = true;
break;
if(!found1)
[Link]("Element not found");
break;
case 2:
int low = 0, high = n - 1;
boolean found2 = false;
while(low <= high) {
int mid = (low + high) / 2;
if(arr[mid] == key) {
[Link]("Element found at position: " + (mid + 1));
found2 = true;
break;
else if(arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
if(!found2)
[Link]("Element not found");
break;
default:
[Link]("Invalid choice");
[Link]();
}
OUTPUT:
Enter number of elements: 5
Enter elements:
10 20 30 40 50
Enter element to search: 30
1. Linear Search
2. Binary Search
Choose method: 1
Element found at position: 3
Flow chart: