Download - COMPUTER PROGRAMMING UNIT 1 Lecture 6
COMPUTER PROGRAMMING
Lecture 06
Prepared By Mr. V. S. Patil Dept (CSE)/AEC
Unit 1 Problem SolvingSyllabus
Prepared By Mr. V. S. Patil Dept (CSE)/AEC
2
1Understanding Linear Search
Understanding Binary Search
Objectives
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.
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
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
Linear Search
7 12 5 22 13 32DATA
1 2 3 4 5 6
DATA
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
DATA
DATA
DATA
Video of linear search
• View video
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
Continue..
6. If(ITEM>Mid)
7. Lo=Lo+Mid
8. Repeat step 2
9. if(mid==ITEM)
10.ITEM found at Mid
11. Else ITEM not in list
12.Stop
Binary Search
• (Binary search. Given value and sorted array a[ ], find index isuch that a[i] = value, or report that no such index exists.
• Invariant. Algorithm maintains a[lo] value a[hi].• Ex. Binary search for 33.
Binary Search
Binary Search
Binary Search
ITEM= 33 Found at 4th position
Binary search video
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