This preview shows pages 1–2. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Problems and Algorithms Linear Search (A[1..n],v) Pseudo code: 1. // Input: array of n numbers a[1..n] 2. // and key value v to be searched for. 3. // Output: an integer index i into the array a (1<=i<=n) 4. // such that A[i] = v, or the special value NIL if v isnt found. 5. Integer i 6. For i < to n 7. Do if A[i]= v 8. The return i 9. Return nil Definition: (see input and output in pseudo code) Loop Invariant: The first i=1 items in A[1..i1] do not contain the searched for key value v. Asymptotic runtime: worst case = (H) n Find max in an Array: set max = i, and compare i to every other element in the array, switching i with the comparison element if that element is greater than i. Loop invariant: max is the largest number in the subarray A[1..i1]. Binary Search (A[L..R],v) Pseudo code: 1. //Input: a subarray of numbers A[L..R], L <= R, known to be already 2. // sorted nondescending (i.e. in increasing order except for equal items); 3. // and a key value v o be searched for. 4. //Output: an integer index j into the array A(L<=j<=R) 5. // Such that A[j] = v, or the special value nil if v is not found. 6. Integer mid // index of item at the middle of the array 7. If L > R 8. The return nil //Key v isnt anywhere in the array 9. Else mid < [(L+R)/2] 10. If A[mid] = v 11. Then return mid //Key v has been found, at A[mid] 12. Else if v < A[mid] 13. Then return BinarySearch (A[L..(mid1)],v) 14. Else return BinarySearch (A[(mid + 1)..R],v) Definition: Used to search for a value in a sorted array. Looks at the middle value in the array Used to search for a value in a sorted array....
View
Full
Document
This note was uploaded on 04/07/2008 for the course CSE 340 taught by Professor Baird during the Fall '08 term at Lehigh University .
 Fall '08
 Baird
 Algorithms

Click to edit the document details