DEV Community

Cover image for Hacktoberfest! Last PR! Dutch National Flag~
Thanh Tien Phat Nguyen
Thanh Tien Phat Nguyen

Posted on

Hacktoberfest! Last PR! Dutch National Flag~

Every party must come to an end. This is the last PR that I made for Hacktoberfest. For the first time that I realize how fun it was. To be honest, each pull request literally pulls you up.

My last PR is not something big. I was just doing something ordinary my self. I worked on Dutch National Flag problem. The problem is there is an array consisting only 0, 1 and 2. How to sort the array in the linear time complexity.
Alt Text
Well, the problem did raise the curiosity in my head which makes me want to try it. Here is my solution:

 public static void SortingArray(int a[]){
        // Count the number of zero, one
        int zeros, ones, k;
        zeros = ones = k = 0;

        for (int i = 0; i < a.length ; i++){
            if (a[i] == 0 )
            {
                zeros++;
            }
            if (a[i] == 1 )
            {
                ones++;
            }
        }

        // fill zero in the first positions of the array
        while(zeros-- != 0){
            a[k++] = 0;
        }

        //fill one in the next empty position
        while (ones-- != 0){
            a[k++] = 1;
        }

        // fill twos in the left positions
        while (k < a.length){
            a[k++] = 2;
        }
        System.out.println(Arrays.toString(a));

    }
Enter fullscreen mode Exit fullscreen mode

I would like to explain a bit about my way to approach the problem. To sort the array that only contains 0, 1 and 2, I first count the number of 0 and 1 in that array. Then I over-write the existing array of which the n first positions are filled with n zeros. The next m positions are filled with m ones. The left positions are filled with twos. Therefore, the array is sorted in linear time complexity.

My last PR is not something significant but I would like to share it to you guys. Every git push I have made is a push for me to get out of my comfort zone and started to be more proactive myself.

Top comments (0)