This document provides information about linear and binary search algorithms. It discusses the basic concepts of linear search, including traversing an unsorted list sequentially until the target element is found or the list is exhausted. It also outlines the steps of a linear search algorithm. Next, it introduces binary search, which can only be used on sorted lists, and outlines the iterative process of comparing the target to the midpoint and narrowing the search range accordingly. Examples of both linear and binary search are given. Finally, it provides a few review questions related to searching concepts.
4. Linear Search: A Simple Search
•A search traverses the collection until
–The desired element is found
–Or the collection is exhausted
•If the collection is ordered, I might not have to look at all
elements
–I can stop looking when I know the element cannot be in
the collection.
5. Algorithm of Linear search
(Linear Search) LINEAR(DATA, N, ITEM, LOC)
Here DATA is an linear array with N element and ITEM is a given
item of information .This algorithm find the location LOC of
ITEM in the DATA or Sets LOC:=0. IF Search is unsuccessful.
1. [Insert ITEM at the end of DATA].
Set DATA[N+1]:=ITEM
2. [Initialize counter] set LOC:=1
1
2
6. Continue..
3. [Search for item].
Repeat while DATA[LOC]=!ITEM
Set LOC:=LOC+1
[End of loop]
4 [Successful?] if LOC=N+1 then:
Set LOC:=0.
Exit
3
4
5
7. Linear Search
7 12 5 22 13 32DAT
A
1 2 3 4 5 6
DAT
A
7 12 5 22 13 32
1 2 3 4 5 6
7 12 5 22 13 32
1 2 3 4 5 6
7 12 5 22 13 32
1 2 3 4 5 6
ITEM= 13
7 12 5 22 13 32
1 2 3 4 5 6
Item Found at
LOC=5
DAT
A
DAT
A
DAT
A
9. Binary Search
•BINARY(DATA, N, ITEM, Lo, Hi, Mid)
Here DATA is an array with N element and ITEM is a given
item of information .This algorithm find the location ITEM in
the DATA.
1.Initially Lo=0 and Hi= N+1
2.Find Mid=(Lo+Hi)/2
3.If(ITEM<Mid)
4.Hi=Mid-1
5.Repeat step 2
11. Binary Search
• (Binary search. Given value and sorted array a[ ], find
index i
such that a[i] = value, or report that no such index exists.
• Invariant. Algorithm maintains a[lo] ≤ value ≤ a[hi].
• Ex. Binary search for 33.
16. Question Bank
1. What is mean by searching?
• Explain linear search with suitable example
1. With the help of binary search algorithm find 7 in given
list.
12 45 34 67 98 42 23 7 87