Here is an algorithm to sort 4 elements with 5
comparisons and 5 swap instructions (swap swaps the contents of its arguments)
. Here is one
input a,b,c,d
output: sorted(a,b,c,d) - a < b < c < d
Algorithm:
if (a > b) swap(a,b)
if (c > d) swap(c,d)
if (b > d) swap(b,d) // d is the highest
if (a > c) swap(a,c) // a is the smallest
if (b > c) swap (b,c)
Answer the following questions.
- How many swap instructions will be executed for the input (a,b,c,d order) 100, 20, 30, 40?
- How many swap instructions will be executed for the input (a,b,c,d order)
30,100,200,40?
- Give an input where all the five swap instructions are executed.
(Hint: Think back from the output)