DATA STRUCTURES & ALGORITHMS
Tutorial 6 Questions
SORTING ALGORITHMS
Required Questions
Question 1.
Many operations can be performed faster on sorted than on unsorted data. For which of
the following operations is this the case?
a. checking whether one word is an anagram of another word, e.g., plum and lump
b. findin the minimum value.
c. computing an average of values
d. finding the middle value (the median)
e. finding the value that appears most frequently in the data
Question 2.
In which case, the following sorting algorithm is fastest/slowest and what is the
complexity in that case? Explain.
a. insertion sort
b. selection sort
c. bubble sort
d. quick sort
Question 3.
Consider the sequence of integers
S = {5, 8, 2, 4, 3, 6, 1, 7}
For each of the following sorting algorithms, indicate the sequence S after executing each
step of the algorithm as it sorts this sequence:
a. insertion sort
b. selection sort
c. heap sort
d. bubble sort
e. merge sort
Question 4.
Consider the sequence of integers
1
T = {1, 9, 2, 6, 4, 8, 0, 7}
Indicate the sequence T after executing each step of the Cocktail sort algorithm (see
Appendix) as it sorts this sequence.
Advanced Questions
Question 5.
A variant of the bubble sorting algorithm is the so-called odd-even transposition sort .
Like bubble sort, this algorithm a total of n-1 passes through the array. Each pass consists
of two phases: The first phase compares array[i] with array[i+1] and swaps them if
necessary for all the odd values of of i. The second phase does the same for the even
values of i.
a. Show that the array is guaranteed to be sorted after n-1 passes.
b. What is the running time of this algorithm?
Appendix – Cocktail sort
Cocktail sort, also known as bidirectional bubble sort, cocktail shaker sort, shaker
sort (which can also refer to a variant of selection sort), ripple sort, shuffle sort, shuttle
sort or happy hour sort, is a variation of bubble sort that is both a stable sorting
algorithm and a comparison sort. The algorithm differs from bubble sort in that it sorts in
both directions on each pass through the list. This sorting algorithm is only marginally
more difficult to implement than bubble sort, and solves the problem with so-called
turtles in bubble sort. (Wikipedia)
Pseudocode
procedure cocktailSort( A : list of sortable items ) defined as:
do
swapped := false
for each i in 0 to length( A ) - 2 do:
if A[ i ] > A[ i + 1 ] then // test whether the two elements are in the
wrong order
swap( A[ i ], A[ i + 1 ] ) // let the two elements change places
swapped := true
end if
end for
if swapped = false then
// we can exit the outer loop here if no swaps occurred.
break do-while loop
end if
swapped := false
for each i in length( A ) - 2 to 0 do:
if A[ i ] > A[ i + 1 ] then
swap( A[ i ], A[ i + 1 ] )
swapped := true
end if
end for
while swapped // if no elements have been swapped, then the list is
sorted
2
end procedure
-- End --
3
© Copyright 2025 Paperzz