Page 286 - Computer science 868 Class 12
P. 286
14 }
15 if (pos!=-1)
16 System.out.println(n + " found at index " + i + " in the array");
17 else
18 System.out.println(n + " not found in the array");
19 }
20 }
The output of the preceding program is as follows:
9.8 found at index 3 in the array
Binary Search
It is a searching technique in which an array is divided two halves and searching takes place in either of the two halves,
depending on the element to be searched. The array should already be sorted in ascending order now, if the number
to be searched is greater than the middle element, searching is done in the second half else done in the first half.
The three conditions that arise are:
• If the element to be searched is the same as the middle element, then the search is completed and the location of
the number is printed or returned.
• If the element to be searched is smaller than the middle element, then the whole process is repeated with the first
half of the list.
• If the element to be searched is greater than the middle element, then the whole process is repeated with the
second half of the list.
Program 5 Write a program to input 5 names in sorted order and search a name in the array.
1 import java.util.*;
2 class Binary_search
3 {
4 public static void main(String ns)
5 {
6 Scanner sc= new Scanner(System.in);
7 String name[]=new String[5];
8 int i,pos=-1,min=0,mid=0,max=4;
9 for (i=0; i<5; i++)
10 { System.out.print("Enter a name : ");
11 name[i] =sc.next();
12 }
13
284284 Touchpad Computer Science-XII

