computer programming unit 1 lecture 6

Download COMPUTER PROGRAMMING UNIT 1 Lecture 6

Post on 19-Aug-2015

28 views

Category:

Engineering

3 download

Embed Size (px)

TRANSCRIPT

  1. 1. COMPUTER PROGRAMMING Lecture 06 Prepared By Mr. V. S. Patil Dept (CSE)/AEC
  2. 2. Unit 1 Problem Solving Syllabus Prepared By Mr. V. S. Patil Dept (CSE)/AEC
  3. 3. 2 1 Understanding Linear Search Understanding Binary Search Objectives
  4. 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. 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. 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. 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
  8. 8. Video of linear search View video
  9. 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
  10. 10. 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
  11. 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.
  12. 12. Binary Search
  13. 13. Binary Search
  14. 14. Binary Search ITEM= 33 Found at 4th position
  15. 15. Binary search video
  16. 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