Saturday, May 25, 2013

Dutch national flag problem

Problem:
You are given an array of 1's 2's and 3's. Sort this list so the 1's are first, the 2's come second, and the 3's come third.

Ex: Input [1, 3, 3, 2, 1]
Output [1, 1, 2, 3, 3]

But there is a catch!! The algorithm must be one pass, which means no merge/quick sort. Also no extra list allocations are allowed, which means no bucket/radix/counting sorts.

You are only permitted to swap elements.

Solution:
One algorithm is to have the top group grow down from the top of the array, the bottom group grow up from the bottom, and keep the middle group just above the bottom. The algorithm stores the locations just below the top group, just above the bottom, and just above the middle in three indexes. At each step, examine the element just above the middle. If it belongs to the top group, swap it with the element just below the top. If it belongs in the bottom, swap it with the element just above the bottom. If it is in the middle, leave it. Update the appropriate index.

public class DutchNationalFlag {
 
    public static void dutchFlagSort(int[] arr, int p, int k) {
        int p_index = 0;
        int k_index = arr.length - 1;
        for (int i = 0; i <= k_index;) {
                if (arr[i] == p) {
                        swap(arr, i, p_index);
                        p_index++;
                        i++;
                }
                else if (arr[i] >= k) {
                        swap(arr, i, k_index);
                        k_index--;
                }
                else {
                        i++;
                }
        }
    }
 
    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
 
 }


Complexity:
time - O(n)
space - O(1)
Links and credits:
http://www.careercup.com/question?id=18824667
http://en.wikipedia.org/wiki/Dutch_national_flag_problem


No comments:

Post a Comment