{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

lecture15

# lecture15 - Lecture 15 Algorithms Algorithms Many problems...

This preview shows pages 1–9. Sign up to view the full content.

Lecture 15 Algorithms

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Algorithms Many problems involving discrete structures are solved using algorithms. An algorithm is a finite set of precise instructions for performing a computation that solves a problem Not too different from a proof
Searching Algorithms Input: a sequence of n distinct integers a 1 , a 2 , …, a n ; and an integer x Goal: to find if x is in the sequence Output: 0 if x is not in the sequence, the index of x otherwise

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Linear Search Algorithm procedure linear_search ( x : integer; a 1 , a 2 , …, a n : integers) location = 0 for ( i =1 to n) if a i = x then location := i break { location is the subscript of the term that equals x, or it is 0 if x is not found}
Exercise Prove that the linear search algorithm is correct

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
What is the running time of linear_search? Well, it depends not only the size of the input sequence, but also the location of x For such cases, often we use worst case analysis How many steps will linear_search take in the worst case? Can you do better than this in general?
Binary Search When the input is sorted, we can use this structure to find a more efficient search algorithm

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Binary Search procedure binary_search ( x : integer; a 1 , a 2 , …, a n : increasing integers) i := 1 { i is left endpoint of search interval } j := n { j is right endpoint of search interval } while i < j begin m := ( i + j )/2 { m is the point in the middle } if x > a m then i := m +1 else j := m end if x = a i then location := i else location := 0 { location is the subscript that equals x, or it is 0 if x is not found}
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 31

lecture15 - Lecture 15 Algorithms Algorithms Many problems...

This preview shows document pages 1 - 9. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online