Final (AY23/24)
Last updated
Last updated
Problems
Question paper without answers:
Question paper with answers:
Insertion sort is fast when it comes to sorting an almost sorted list.
Here is the table summarise the best-case, worst-case time complexity for different sorting algorithms:
Bubble Sort
0
Insertion Sort
0
Selection Sort
Notice that in this question, we are talking about the number of swaps, not the running time. So, for the selection sort we are always making times of swap.
Below is the table summarises the number of swap needed for different sorting algorithms:
Bubble Sort
0
Insertion Sort
0
Selection Sort
This kind of sequence (each binary number is one-bit different from its previous) is called grey code! Amazing right!
In this problem, it utilises a hidden information: that is the string is intialized to be all 0! So, it is safe for the first line of our recursion to be just generate(str, n, k + 1)
since once it reaches the end, it will print all 0
.
Then our idea may be a bit clearer, we modify our current bit str[k]
to be different from what we print out previously, and then print it out by calling generate(str, n, k + 1)
again.
To make our mind clearer, Line 1 is to generate the "previous" binary string, then Line 2 modifies the "next" binary string to be exactly one bit different from the previous and then print it out calling the substring recursively.