Searching and Sorting 569
printf("
The number of iterations are: %d",j);
}
else printf("n Number Is not found ■);
getchO ;
}
OUTPUT:
Enter the array elements: 12 5 8 7
Enter the number from the list for searching: 5
The position of element 5 is: 3
The number of iterations are: 3
Explanation In the above program an array of five elements is declared. Numbers are entered
and stored in the array. The number whose position is to be located is entered from the keyboard.
The entire array is scanned and the given number is checked with all the elements one by one.
When the element is found, the
break statement terminates the loop. The number of iterations
and location of the element in the array are always same. This is because, as soon as an element is
found loop is terminated. The array elements are accessed according to the iterations of the loop.
The ' if' statement checks the value of j, and if it is less than five, the position and number of
iterations are displayed else message "Number is not found" is displayed.
16.4 BINARY SEARCH
Binary search offers comparatively lesser number of iterations than the linear search.
In this method, the elements are not searched sequentially like linear search. Instead of this, two
compartments of the list are done. Each compartment will be having an equal number of items.
The lower compartment contains approximately half the elements and this compartment is called
lower half. The upper compartment containing upper elements is upper half. Then the given element
is searched. The element may be found in the lower half or the upper half of the compartments. It
creates two parts of the lists hence it is known as binary search.
Binary search is quicker than the linear search. However, it cannot be applied on unsorted data
structure. Before applying binary search, the linear data structure must be sorted in either ascending
or descending order. The binary search is based on the approach divide-and-conquer. In this method,
the element to be searched is compared with the middle element. If the match is observed then the
element is successfully searched. Otherwise the element is compared with the items of the two
compartments, that is, it is compared with the items falling under the lower half or upper half
compartments. If the expected item is less than the middle element, the lower half compartment is
search. If it is larger than the middle, upper half compartment ^s searched. These steps are illustrated
in Fig. 16.3.