After learning elementary sorts, selection sort, insertion sort & heap sort from sedgewick course in Coursera.
Selection sort - final sorted order starts forming every iteration
Insertion sort - Ascending order(not final) starts forming every iteration.
Heap sort - Aggressive version of insertion sort.
I have an assignment, in the above mentioned course, after learning sort algorithms(shown above),
Dutch national flag. Given an array of
n
buckets, each containing a red, white, or blue pebble, sort them by color. The allowed operations are:
swap(i,j)
:swap
the pebble in bucketi
with the pebble in bucketj
.
color(i)
: color of pebble in bucketi
.The performance requirements are as follows:
At most
n
calls tocolor()
.At most
n
calls toswap()
.Constant extra space.
By reading this question,
From the performance requirements, given, I get a hint that n
swaps are required(at-most). From this hint, I think about,
1) Insertion sort that ensures n swaps for n inversion pairs.
2)
Am assuming colors that are stored in buckets, there is very great chance that, similar colors sit closer, given n buckets. This leads to a situation of partially sorted array, where an array is partially sorted, if the number of inversions <= cn
.
Based on these above two conclusions,
Question:
1)
Is the thought process correct in deducing to insertion sort, as solution?
2)
What is the hash function to hash colors and insert colors in as partially sorted array? Do I need linear probing method?
3) Why do we need extra space, as given in question? Because Insertion sort is in-place algorithm
Note: To confirm my thought process, before writing code
To elaborate solution for this problem, you don't need mentioned algorithms.
Instead become familiar with partition routine implementations of Quick Sort - it would really helpful.
P.S.
No, you are wrong, it is completely different approach
You can consider how Shell sort does exploit Insert sort internally