Binary searching is efficient one among the searching method. It finds the mid item. Using the mid item, divide the array elements into two halves. Checks each half and repeat the process for all the elements.
Java program to illustrate binary searching using functions:
This
program gives you way to implement binary search in java. Here are the steps.
·
Include the built in files
- · Create a public class with main function.
- · Inputs: number of elements in the array, array elements, the data is searched.
· Logic:
- · Two variable h(high),l(low) where l=0, h =length of the array -1.
- · Check whether l is less than h ,continue the loop.
- · Find the mid value by adding l,h value and divide by 2.
- · If any array element is matched with the data to be searched, return the mid value.
- · Else, the array element is less than data assign l as mid+1.
- · Else, assign the h value as mid -1.
Program:
import java.util.Arrays;
import java.util.Scanner;
public class bSearch {
public static void
main(String[] args) {
Scanner
scanner = new Scanner(System.in);
System.out.print("Enter the number of elements");
int no =
scanner.nextInt(); // Read the number of elements
int[] a = new
int[no]; // Array declaration
int j=0,key=0;
System.out.println("Enter " + no + " elements: ");
for (j = 0;
j< no; j++) {
a[j] =
scanner.nextInt(); // get the array elements
}
System.out.println("Enter the data to be searched");
int data =
scanner.nextInt();
int in =
binaryS(a,data);
if (in != -1)
{
System.out.println("Element found at index: " + in);
} else {
System.out.println("Element not found");
}
}
public static int
binaryS(int[] a, int data) {
int l = 0;
int h =
a.length - 1;
while (l <=
h) {
int mid =
(l + h) / 2;
if (a[mid]
== data) {
return
mid;
} else if
(a[mid] < data) {
l =
mid + 1;
} else {
h =
mid - 1;
}
}
return -1;
}
}
Output:
C:\raji\blog>javac bSearch.java
C:\raji\blog>java bSearch
Enter the number of elements4
Enter 4 elements:
98
56
23
45
Enter the data to be searched
56
Element found at index: 1
This is the way of implementing binary search program in java using functions.
No comments:
Post a Comment