DEV Community

Cover image for Day 27: Bucket Sort
Matt Ryan
Matt Ryan

Posted on

3 3

Day 27: Bucket Sort

import java.util.Random;



public class Bucket_Sort 

{

    static int[] sort(int[] sequence, int maxValue) 

    {

        // Bucket Sort

        int[] Bucket = new int[maxValue + 1];

        int[] sorted_sequence = new int[sequence.length];



        for (int i = 0; i < sequence.length; i++)

            Bucket[sequence[i]]++;



        int outPos = 0;

        for (int i = 0; i < Bucket.length; i++)

            for (int j = 0; j < Bucket[i]; j++)

                sorted_sequence[outPos++] = i;



        return sorted_sequence;

    }



    static void printSequence(int[] sorted_sequence) 

    {

        for (int i = 0; i < sorted_sequence.length; i++)

            System.out.print(sorted_sequence[i] + " ");

    }



    static int maxValue(int[] sequence) 

    {

        int maxValue = 0;

        for (int i = 0; i < sequence.length; i++)

            if (sequence[i] > maxValue)

                maxValue = sequence[i];

        return maxValue;

    }



    public static void main(String args[]) 

    {

        System.out

                .println("Sorting of randomly generated numbers using BUCKET SORT");

        Random random = new Random();

        int N = 20;

        int[] sequence = new int[N];



        for (int i = 0; i < N; i++)

            sequence[i] = Math.abs(random.nextInt(100));



        int maxValue = maxValue(sequence);



        System.out.println("\nOriginal Sequence: ");

        printSequence(sequence);



        System.out.println("\nSorted Sequence: ");

        printSequence(sort(sequence, maxValue));

    }

}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay