Computer-Enabled
Problem Solving
ITM207
Searching &
Sorting
© Copyright Youcef Derbal, 2016-2024
1
Agenda
• Searching
• Sequential Search
• Binary Search
• Sorting
• Bubble Sort
• Insertion Sort
• Selection Sort
© Copyright Youcef Derbal, 2016-2024
2
Searching
Searching for an “element” in an array is looking for its position
(index ) in the array
Strategies
➢Randomly pick one element and check if it is what we are
looking for, then repeat this process until the target element is
found, or all the elements are visited and the target is not found
➢Start from the left/right and check one element at a time.
➢Design an efficient algorithm that takes advantage of what we
might know about the organization of the elements within the
data structure, an array in this case.
66
77
89
49
78
© Copyright Youcef Derbal, 2016-2024
56
3
Sequential Search
66
78
77
89
49
78
56
compare
Searching for the mark 78, i.e. looking for its
position in the array.
• Consider the first element in the array
• Compare its value against the target value
• If the two values match, the target is found
(search ends), otherwise consider the next
element in the array, until reaching the end of
the array
© Copyright Youcef Derbal, 2016-2024
4
Sequential Search
found : Boolean variable to indicate the status
of the search
pos : record the position, in the array, of the
target when it is found
1. Start
2. found false
3. pos -1
4. i 1 (the position of the first element of marks)
5. If marks[i] = x (the target value ) then
▪ found true
▪ pos i
▪ Go to step 8
6. (otherwise) i i + 1
7. if i > Length_of(marks) go to 8 otherwise go to
step 5
8. End
© Copyright Youcef Derbal, 2016-2024
5
Sequential Search
found : Boolean variable to indicate the
status of the search
pos : The position, in the array, of the
target when it is found
• The search is stopped when the
“mark” we are looking for is
found ( found = true)
OR
• The end of the array is reached :
i > Length_of(marks)
6
© Copyright Youcef Derbal, 2016-2024
Sequential Search
• How would we change the sequential search
algorithm if the array was sorted ? ( data
organization that we can leverage)
40
• Example: What is the position of “52” in this
array. The array is assumed to be sorted in
increasing value.
• Starting from the top of the sorted array, the
search should stop once we reach 55 ( and
conclude that the value 52 will not be found in
the array ) because all the remaining elements
are greater than or equal to 55 , which is greater
than 52.
© Copyright Youcef Derbal, 2016-2024
50
55
60
70
90
7
Sequential Search
of a Sorted Array
• The search is stopped when
we find the target or we
encounter an array element
with a value greater than
the target
• We implemented the loop
exit by setting i to a value
higher than the length of
the array to make the
Boolean expression
i > length_of(marks) true:
i length_of(marks) + 1
© Copyright Youcef Derbal, 2016-2024
8
Binary Search
Sequential search
Search starts from the first element of the array and proceeds to
the next elements one after the other until the target item is
found or the entire array has been traversed.
Binary search – Array must be already sorted
Start the search from the middle of the sorted array to find the
item. If not found discard half of the array that cannot possibly
include the item and repeat the search starting from the middle
of the other half.
© Copyright Youcef Derbal, 2016-2024
9
Binary Search
marks
Searching for the item x = 56
index
first
pivot
pivot floor( (first+last)/2 ) : integer division
(Middle)
last
pivot = floor(8/2) = 4
1. if x = marks[pivot]
then we found our item – it is located at the pivot
position which is 4. The search process is completed
2. if x > marks[pivot]
then search in the array half {pivot +1 to last} and
ignore the other half – it can’t contain the item we
are searching for.
3. if x < marks[pivot]
then search in the array half {first to pivot-1} and
ignore the other half – it can’t contain the item we
are searching for
4. Stop the search when first > last
© Copyright Youcef Derbal, 2016-2024
10
Binary Search
Searching for the item x = 56
marks
1st iteration :
first = 1, last = 7, pivot = floor((1+7)/2) = 4
marks[4], which is 34, is not equal to the
target mark 56.
56 > marks[4] ? Yes, then search in the array
portion (pivot+1 to last)
first
pivot
last
marks
2nd iteration :
first pivot+1 : 5
last did not change – still 7
pivot floor((first+last)/2) :
floor((5+7)/2) = 6
first
pivot
last
marks[pivot] = marks[6] is equal to the
target mark 56 … Found!
© Copyright Youcef Derbal, 2016-2024
11
Binary Search
• Search Stops when the item
is found (found=true) or the
next half portion of the
array to be considered is
delimited by a first index
that is greater than its last
index! (first > last)
• Note that the pivot is
computed using the floor()
function, i.e. integer division
© Copyright Youcef Derbal, 2016-2024
12
Sorting
Sorting a set of records (strings, numbers, objects
etc..) means putting them in some order.
Example: we may want to sort archived email messages in a
chronological order to look for an email received within a specific
week.
• Sorting a large number of records is time consuming,
effective sorting strategies are needed.
• Focus on three classical sorting algorithms: Selection,
Bubble and Insertion.
• These algorithms are compared vis-à-vis their
performance - measured using the run time required to
sort a set ( an array) of records.
© Copyright Youcef Derbal, 2016-2024
13
Sorting Algorithms
• In general, sorting solutions
consist of multiple iterations of
pairing array elements and
swapping their places, if
necessary.
• Sorting solutions are
distinguished by their pairing
strategies
© Copyright Youcef Derbal, 2016-2024
14
Selection Sort
Algorithm Index position
1st Iteration
Smallest is in position 1
• The entire array is labeled as
unsorted
7
56
11
12
11
12
Unsorted
• Find the position of the smallest
element among the unsorted
ones
• Pair the first unsorted element
and the smallest element
34
7
34
56
Pair the element in position 1 with the smallest
one, which is also in position 1.
Unsorted
Sorted
• Swap the positions of the first
unsorted element and the
smallest element
© Copyright Youcef Derbal, 2016-2024
7
34
56
11
12
Swap the element in position 1 with the smallest
one, which is also in position 1.
15
Selection Sort
Algorithm First
Unsorted
Smallest is in position 4
2nd Iteration
• Find the position of the smallest element
among the unsorted ones
• Pair the first unsorted element ( starting
index position 1) and the smallest
element
7
34
56
11
12
7
34
56
11
12
Pair the element in position 2 with the smallest
one, which is in position 4.
Unsorted
Sorted
• Swap the positions of the first unsorted
element and the smallest element
© Copyright Youcef Derbal, 2016-2024
7
11
56
34
12
Swap the element in position 2 with the smallest
one, which is in position 4.
16
Selection Sort
Stop when unsorted = n
© Copyright Youcef Derbal, 2016-2024
17
Selection Sort : findIndexOfSmallest
•
•
•
Variables :
• Unsorted : position of the first unsorted element
• indexOfSmallest : position of the smallest element
among the unsorted
Finding the lowest/smallest value among the unsorted is
the same as finding the lowest/highest mark.
The only difference - the search for the smallest
concerns the unsorted part of the array, which is
changing in size.
© Copyright Youcef Derbal, 2016-2024
18
Selection Sort
swap
swap
temp
34
3
1
unsorted
11
7
34 56 11 12
2
© Copyright Youcef Derbal, 2016-2024
34
indexOfSmallest
19
Bubble Sort
This is a simple sorting strategy were every element is compared with their adjacent
element as follows :
1st Iteration :
1. Pair each unsorted element with its adjacent unsorted element starting from the
last unsorted element
2. Swap the elements in the pair if the one with the higher index (Bottom one) is
lower.
20
© Copyright Youcef Derbal, 2016-2024
Bubble Sort – Second Iteration
2nd Iteration :
1. Pair each unsorted element with its adjacent unsorted element starting from the
last unsorted element
2. Swap the elements in the pair if the one with the higher index (Bottom one) is
lower.
21
© Copyright Youcef Derbal, 2016-2024
Bubble Sort
© Copyright Youcef Derbal, 2016-2024
22
Bubble Sort - implementation
For each sorting iteration (counted
using i) each unsorted j-th element
is paired with their adjacent
element. Hence we need two
loops:
• To perform multiple iterations, we
need a loop with a counter i
starting from 1 and incremented
by 1 to n
• For each iteration (value of i ), an
inner loop is needed with j as a
counter starting from n and
decremented by 1 to i+1
i = 1
j = 5, 4, 3, 2
i = 2
j = 5, 4, 3
i = 3
j = 5, 4
i = 4
j = 5, 4
j=5
i=1
7
34
56
11
© Copyright Youcef Derbal, 2016-2024
12
23
Bubble Sort
© Copyright Youcef Derbal, 2016-2024
24
Bubble Sort – Improvement
• Slow & Inefficient
• Observation – if no swap is needed in any one of
the iterations, then the array is already sorted –
no need to continue.
• This observation can be used to improve the
Bubble sort algorithm.
© Copyright Youcef Derbal, 2016-2024
25
Bubble Sort
Improvement
• Use a flag ( swapped) to track whether
or not a swap was performed during
an iteration
Swap
© Copyright Youcef Derbal, 2016-2024
26
Insertion Sort
Index position
Insert elements in the sorted portion of the array one at a time
© Copyright Youcef Derbal, 2016-2024
27
Insertion Sort
Variables:
• current : position of the second unsorted element
• index : position of elements lower in position than current
© Copyright Youcef Derbal, 2016-2024
28
Insertion Sort
sortInsert
sortInsert
Index-1
7
7
Index-1
7
index
34
56
Index-1
index
34
11
56
12
34
56
12
11
12
Index current
index
11
29
© Copyright Youcef Derbal, 2016-2024
Sorting Algorithms
Efficiency Comparison
The efficiency of an algorithm is said to be an O(n) (Order of
magnitude n) if the computation time is a linear function of n.
Ex: 10 records requiring 10 x T seconds, where T can be any real
number.
Algorithm Comparison
• Computation time (speed)
• Memory use
• Best, Worst and Average performance
ex: Best n, Worst 3n, Average 2n
The speed of an insertion algorithm can be better for smaller
arrays of records, it lags in efficiency behind more complex
sorting algorithm such as quicksort, for large record sets.
© Copyright Youcef Derbal, 2016-2024
30
Performance of Sorting Algorithms
Sorting Algorithm
Best
Average
Worst
Memory
Stability
Bubble
n
n2
n2
1
Stable
Selection
n2
n2
n2
1
Not Stable
Insertion
n
n2
n2
1
Stable
Merge Sort
n log(n)
n log(n)
n log(n)
n (worst)
Stable
Quicksort
n log(n)
n2
n (worst)
Not stable
Heapsort
n log(n)
n log(n)
1
Not stable
n : number of records
A sort algorithm is stable if it maintains the order of elements that have the same “sort order”
stable
unstable
© Copyright Youcef Derbal, 2016-2024
31