Sunday, June 9, 2013

Given a collection of 1 million integers, All ranging between 1 to 9, how would you sort them in Big O(n) time ?

This is a typical Integer Sorting problem with a constraint that the number range to sort is very limited in spite 1 million total entries. Integer Sorting with limited range is achieved efficiently with Bucket Sorting.


TIP- What does Wiki Says about Sorting ?

Bucket sort, counting sort, radix sort, and van Emde Boas tree sorting all work best when the key size is small; for large enough keys, they become slower than comparison sorting
algorithms…

Integer Sorting Techniques : http://en.wikipedia.org/wiki/Integer_sorting#Algorithms_for_few_items
Sorting Algorithms : http://en.wikipedia.org/wiki/Sorting_algorithm


Algorithm

Create a array of size 9 and at each index store the occurrence count of the respective integers. Doing this will achieve this sorting with time complexity of Big O(n) and even the memory requirements are minimized. In Order to print the output just traverse the above created array.

public class BucketSort {
    public int[] sort(int[] array, int min, int max) {
        int range = max - min + 1;
        int[] result = new int[range];
        for (int i: array) {
            result[i]++;
        }
        return result;
    }
}

public class BucketSortTest {@
    Test
    public void testBucketSortFor1To9() {
        int[] array = {
            2, 1, 5, 1, 2, 3, 4, 3, 5, 6, 7, 8, 5, 6, 7, 0
        };
        int[] sort = new BucketSort().sort(array, 0, 8);

        for (int i = 0; i & lt; sort.length; i++) {
            for (int j = 0; j & lt; sort[i]; j++) {
                System.out.println(i);
            }
        }
    }
}

Program output : 0,1,1,2,2,3,3,4,5,5,5,6,6,7,7,8

No comments:

Post a Comment

Your comment will be published after review from moderator