CSE340 Review Sheet Test 1 (03)

# CSE340 Review Sheet Test 1 (03) - Problems and Algorithms...

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
This is the end of the preview. Sign up to access the rest of the 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 isn’t 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..i-1] 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 sub-array A[1..i-1]. Binary Search (A[L..R],v) Pseudo code: 1. //Input: a sub-array of numbers A[L..R], L <= R, known to be already 2. // sorted non-descending (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 isn’t 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..(mid-1)],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

{[ snackBarMessage ]}

### Page1 / 5

CSE340 Review Sheet Test 1 (03) - Problems and Algorithms...

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

View Full Document
Ask a homework question - tutors are online