Lecture 11-12
Lecture 11-12
Discrete Structures
MUHAMMAD UMAR NASIR (LECTURER FCS)
RIPHAH INTERNATIONAL UNIVERSITY LAHORE
Algorithms
What is an algorithm?
3 , 4 , 8 , 1 , 6 , 7 , 15 , 5 , 8 , 2
i ai max
2 (a2) 4 (3<4) 4
3 (a3) 8 (4<8) 8
4 (a4) 1 (8<1) 8
5 (a5) 6 (8<6) 8
6 (a6) 7 (8<7) 8
7 (a7) 15 (8<15) 15
8 (a8) 5 (15<5)15
9 (a9) 8 (15<8)15
10 (a10) 2 (15<2) 15
Linear Search:
It is also called sequential search. It searches an element
sequentially by comparing the searching element with each
element in the list one by one.
procedure linear search(x: integer, a1, a2, . . . , an: distinct
integers)
i := 1
while (i ≤ n and x ≠ ai )
i := i + 1
if i ≤ n then location := i
else location := 0
return location {location is the subscript of the term that
equals x, or is 0 if x is not found}
Linear Search:
Search 5 from list 2 , 7 , 4 , 10 , 5 , 9
x=5 a1 a2 a3 a4 a5 a6
i=1 2 7 4 10 5 9
x=5 a1 a2 a3 a4 a5 a6
i=2 2 7 4 10 5 9
x=5 a1 a2 a3 a4 a5 a6
i=3 2 7 4 10 5 9
x=5 a1 a2 a3 a4 a5 a6
i=4 2 7 4 10 5 9
x=5 a1 a2 a3 a4 a5 a6
i=5 2 7 4 10 5 9
i=1 2 7 4 10 5 9
x=3 a1 a2 a3 a4 a5 a6
i=2 2 7 4 10 5 9
x=3 a1 a2 a3 a4 a5 a6
i=3 2 7 4 10 5 9
Linear Search:
x=3 a1 a2 a3 a4 a5 a6
i=4 2 7 4 10 5 9
x=3 a1 a2 a3 a4 a5 a6
i=5 2 7 4 10 5 9
x=3 a1 a2 a3 a4 a5 a6
i=6 2 7 4 10 5 9
x=3 a1 a2 a3 a4 a5 a6
i=7 2 7 4 10 5 9
procedure binary search (x: integer, a1, a2, . . . , an: increasing integers)
i := 1{i is left endpoint of search interval}
j := n {j is right endpoint of search interval}
while i < j
m :=
if x > am then i := m + 1
else j := m
if x = ai then location := i
else location := 0
return location{location is the subscript i of the term ai equal to x, or 0 if
x is not found}
Binary Search:
Search 18 from sequence 2 , 3 , 5 , 8 , 10 , 15 , 18 , 30
i m j
2 3 5 8 10 15 18 30
2 3 5 8 10 15 18 30
2 3 5 8 10 15 18 30
2 3 5 8 10 15 18 30
2 3 5 8 10 15 18 30
2 3 5 8 10 15 18 30
2 3 5 8 10 15 18 30
2 3 5 8 10 15 18 30
2 3 5 8 10 15 18 30
Pass 1:
4 7 3 5 2
4 7 3 5 2
4 7 3 5 2
4 3 7 5 2
4 3 5 7 2
4 3 5 2 7
Bubble Sort:
Pass2:
4 3 5 2 7
4 3 5 2 7
3 4 5 2 7
3 4 5 2 7
3 4 2 5 7
Pass3:
3 4 2 5 7
3 4 2 5 7
3 4 2 5 7
3 2 4 5 7
Bubble Sort:
Pass4:
3 2 4 5 7
3 2 4 5 7
2 3 4 5 7
Sorted list is
2 3 4 5 7
Insertion Sort:
Pass 1:
4 7 3 5 2
4 7 3 5 2
4 7 3 5 2
Pass 2:
4 7 3 5 2
4 7 3 5 2
3 4 7 5 2
Insertion Sort:
Pass 3:
3 4 7 5 2
3 4 7 5 2
3 4 5 7 2
Pass 4:
3 4 5 7 2
3 4 5 5 2
2 3 4 5 7
Sorted list is
2 3 4 5 7