Page 273 - computer science (868) class 11
P. 273
Step 2: Repeat the above step.
Position or index 0 1 2 3 4
Ar 1 4 6 8 10
min Max
mid
Middle element is 8 as (3 + 4) / 2 = 7 / 2 = 2 (taking only the integer part)
Now, 8 == ar[3], i.e., 8.
Thus, the searched element is found and the loop breaks.
Since the array is already sorted, the binary search technique is faster than the linear search technique.
Program 9 Write a program to input “n” names in an array and a name to search and print whether the
name is present in the array or not. (Use Binary Search technique)
1 import java.util.*;
2 class Binary_search
3 {
4 public static void main()
5 {
6 Scanner sc= new Scanner(System.in);
7 System.out.print("How many names you want to enter? ");
8 int n = sc.nextInt();
9 String ar[]=new String[n];
10 int i, pos=-1, min=0, mid=0, max=n;
11 String ns;
12 for (i=0; i<n; i++)
13 {
14 System.out.print("Enter a name: ");
15 ar[i] =sc.next();
16 }
17 System.out.print("Enter a name to search: ");
18 ns=sc.next();
19 while(min<max)
20 {
21 mid=(min+max)/2;
22 if(ar[mid].equalsIgnoreCase(ns))
23 {
24 pos=mid;
271
Arrays 271

