Monday, March 16, 2015

Dutch National Flag Algorithm

This Algorithm is used to separate 3 different types of elements together.

For example, lets say an array contains positive, negative, zero(one or more zeros) elements, then using this algorithm, we can bring all zeros together, all positive numbers to the right of zero elements, all negative numbers to the left of zeros.

Note that the positive, negative numbers will not be in sorted order here. We care only about placing negative numbers first, then zeros and then positive numbers.

Code:

import java.util.Arrays;

class DNFAlgo {
        static public void dnfAlgo(int[] in, int pivot) {
                int equal = 0, small = 0, large = in.length - 1;

                while(equal<=large) {
                        if(in[equal] < pivot) {
                                //swap with the small index and increment both small and equal indexes
                                int temp = in[equal];
                                in[equal] = in[small];
                                in[small] = temp;

                                equal++;
                                small++;
                        } else if(in[equal] == pivot) {
                                //just increment equal index
                                equal++;
                        } else {
                                //swap with large index and decrement the large index
                                int temp = in[equal];
                                in[equal] = in[large];
                                in[large] = temp;

                                large--;
                        }
                }
        }

        static public void main(String[] args) {
                int[] in = {2, 0 , -1, -2, 0, 3, -1, 2};

                System.out.println(Arrays.toString(in));

                dnfAlgo(in, 0);

                System.out.println(Arrays.toString(in));
        }
}


eg:


[2, 0, -1, -2, 0, 3, -1, 2]
[-1, -1, -2, 0, 0, 3, 2, 2]

pivot = 0

    equal small large array
    0 0 7 [2, 0, -1, -2, 0, 3, -1, 2]
a[0]=2>0  ==> a[0]<->a[7] 0 0 6 [2, 0, -1, -2, 0, 3, -1, 2]
a[0]=2>0  ==> a[0]<->a[6] 0 0 5 [-1, 0, -1, -2, 0, 3, 2, 2]
a[0]=-1<0 ==> a[0]<->a[0] 1 1 5 [-1, 0, -1, -2, 0, 3, 2, 2]
a[1]=0==0 ==> inc equal  2 1 5 [-1, 0, -1, -2, 0, 3, 2, 2]
a[2]=-1<0 ==> a[2]<->a[1] 3 2 5 [-1, -1, 0, -2, 0, 3, 2, 2]
a[3]=-2<0 ==> a[3]<->a[2] 4 3 5 [-1, -1, -2, 0, 0, 3, 2, 2]
a[4]=0==0 ==> inc equal  5 3 5 [-1, -1, -2, 0, 0, 3, 2, 2]
a[5]=0==0 ==> inc equal  6 3 5 [-1, -1, -,2 0, 0, 3, 2, 2]
condition false

No comments:

Post a Comment