I have been exploring Dikstra partitioning Algorithm. Below are my given:
R = Red
W = White
B = Blue
I have this unpartitioned array.
| W | B | R | W | R | W | B | W | W |
I want it partition in the format: R, W, B consecutively.
| R | ? | W | B |
0 i j k n
Given:
i = 0
j = n
k = n
n = number of elements
Below is my algorithm:
while (i < j)
{
case a[i]:
R : i++;
W : j--; swap(a[i], a[j]);
B : j--; k--; swap(a[i], a[k]); swap(a[i], a[j]);
end case
}
//Done Sorting
The output should be like this:
| R | R | W | W | W | W | W | B | B |
My question are:
- Can I reduce the number of swaps? If yes, how?
- Is the algorithm applicable if there are 4 colors to be partitioned?
Thank you. I really need to understand this concept.