0

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:

  1. Can I reduce the number of swaps? If yes, how?
  2. Is the algorithm applicable if there are 4 colors to be partitioned?

Thank you. I really need to understand this concept.

alyssaeliyah
  • 2,214
  • 6
  • 33
  • 80

1 Answers1

2

As @m69 gave the clue this is the Dutch National Flag problem.

Base on pseudo-code taken from Wikipedia:

A : array of values
i ← 0
j ← 0
n ← size of A - 1

while j ≤ n:
    Case A[i]:
        R:
          swap A[i] and A[j]
          i ← i + 1
          j ← j + 1
        B:
          swap A[j] and A[n]
          n ← n - 1
        W:
          j ← j + 1

Notice that in this case you have 1 less swap in the B case.

For your second question: Yes. Easiest way to do that is to treat the 2 middle part as the same and then make another run on the array and just sort those 2.

Let say you have 4 color: R, W, B, G and you want to sort them in that order. So for the first step: in your switch case have W or B:. After finish run the algorithm run on your array and find index for the first W or B (call it i) and the index of the first G (call it j). Now all you need is to loop between i and j-1 and order the W and B.

This whole process can be done in O(n).

dWinder
  • 11,597
  • 3
  • 24
  • 39