Algorithmic Foundations COMP108 COMP108 Algorithmic Foundations Searching Prudence Wong
Algorithmic Foundations COMP108 Searching Input: n numbers a 1, a 2, …, a n ; and a number X Output: determine if X is in the sequence or not Algorithm (Sequential search): 1. From i=1, compare X with a i one by one as long as i <= n. 2. Stop and report "Found!" when X = a i. 3. Repeat and report "Not Found!" when i > n. 2 (Searching)
Algorithmic Foundations COMP108 Sequential Search six numbers 7number X found! To find 7 3 (Searching)
Algorithmic Foundations COMP108 Sequential Search (2) not found! To find 10 4 (Searching)
Algorithmic Foundations COMP108 Sequential Search – Pseudo Code i = 1 while i <= n do begin if X == a[i] then report "Found!" and stop else i = i+1 end report "Not Found!" Challenge: Modify it to include stopping conditions in the while loop 5 (Searching)
Algorithmic Foundations COMP108 Sequential Search – Pseudo Code i = 1 found = false while i <= n && found==false do begin if X == a[i] then found = true else i = i+1 end if found==true then report "Found!" else report "Not Found!" 6 (Searching)
Algorithmic Foundations COMP108 Number of comparisons? i = 1 while i <= n do begin if X == a[i] then report "Found!" & stop else i = i+1 end report "Not Found!" Best case: X is 1st no. 1 comparison Worst case: X is last OR X is not found n comparisons 7 (Searching) How many comparisons this algorithm requires?
Algorithmic Foundations COMP108 Finding maximum / minimum... 2 nd max / min…
Algorithmic Foundations COMP108 9 (Searching) Finding max from n +ve numbers input: a[1], a[2],..., a[n] M = 0 i = 1 while (i <= n) do begin M = max(M, a[i]) i = i + 1 end output M What about minimum? For simplicity, we assume the function max(X, Y) returns the larger of X & Y
Algorithmic Foundations COMP (Searching) Finding min from n +ve numbers input: a[1], a[2],..., a[n] M = a[1] i = 1 while (i <= n) do begin M = min(M, a[i]) i = i + 1 end output M How many comparisons? n
Algorithmic Foundations COMP (Searching) Finding 1 st and 2 nd min input: a[1], a[2],..., a[n] M1 = min(a[1], a[2]) M2 = max(a[1], a[2]) i = 3 while (i <= n) do begin if (a[i] < M1) then M2 = M1, M1 = a[i] else if (a[i] < M2) then M2 = a[i] i = i + 1 end output M1, M2 Two variables: M1, M2 How to update M1, M2?
Algorithmic Foundations COMP (Searching) Finding location of minimum input: a[1], a[2],..., a[n] loc = 1 // location of the min number i = 2 while (i <= n) do begin if (a[i] < a[loc]) then loc = i i = i + 1 end output a[loc] end of) Iteration loca[loc]i Example a[]={50,30,40,20,10}
Algorithmic Foundations COMP108 Finding min using for-loop Rewrite the above while-loop into a for-loop input: a[1], a[2],..., a[n] loc = 1 for i = 1 to n do begin if (a[i] < a[loc]) then loc = i end output a[loc] 13 (Searching)