3.1 Algorithms: Searching Algorithms Linear Search
3.1 Algorithms: Searching Algorithms Linear Search
3.1 Algorithms
Searching Algorithms
Linear Search
Linear search finds a element in an list by checking every element in the list one by one until it is
found.
Binary Search
If a list is in sorted order, a binary search can be performed to quickly find an element in the list.
To find an element in the list, the algorithm will always narrow its search space by a half every
time a comparison is made until the element is found.
1
ICS 141: Discrete Mathematics I (Fall 2014)
Sorting Algorithms
Bubble Sort
A sorting algorithm where the smaller elements will “bubble” (or “float”) to the beginning of the
list while bigger elements will “sink” to the end of the list.
Insertion Sort
A sorting algorithm where each element becomes “inserted” into the correct position at every
iteration.
3.1 pg 202 # 13
List all the steps used to search for 9 in the sequence 1, 3, 4, 5, 6, 8, 9, 11 using
a) a linear search.
Note that there are eight numbers, so n = 8.
i = 1, 1 6= 9
i = 2, 3 6= 9
i = 3, 4 6= 9
2
ICS 141: Discrete Mathematics I (Fall 2014)
i = 4, 5 6= 9
i = 5, 6 6= 9
i = 6, 8 6= 9
i = 7, 9 = 9
Stop because 9 was found at i = 7
b) a binary search.
Start with 1, 3, 4, 5, 6, 8, 9, 11 (i = 1, j = 8, m = 4)
Compare the m-th element in the list with 9. In this case m = 4, so compare 9 with 5.
Since 9 is not less than 9, take the first half by setting j = 7(= m).
At this moment the algorithm exits the while loop because i is not less than j.
After exiting the loop, compare 9 with the ith element. Since 9 = 9, the algorithms returns
i, which is 7.
3.1 pg 203 # 35
Use the bubble sort to sort 3, 1, 5, 7, 4, showing the lists obtained at each step.
i=2
(1, 3, 5, 4, 7) → (1, 3, 5, 4, 7)
(1, 3, 5, 4, 7) → (1, 3, 5, 4, 7)
(1, 3, 5, 4, 7) → (1, 3, 4, 5, 7)
While we can see that the list is in sorted order, the algorithm does not know that it is correctly
sorted. Hence we keep going until the i-for loop can terminate.
i=3
(1, 3, 4, 5, 7) → (1, 3, 4, 5, 7)
(1, 3, 4, 5, 7) → (1, 3, 4, 5, 7)
3
ICS 141: Discrete Mathematics I (Fall 2014)
i=4
(1, 3, 4, 5, 7) → (1, 3, 4, 5, 7)
3.1 pg 203 # 39
Use the insertion sort to sort 3, 1, 5, 7, 4, showing the lists obtained at each step.