Bubble Sort

I did some more comparative programming around Bubble Sort recently which I decided to post here, to both save it for myself and share with others. This time rather than posting multiple entries (one for each language) I have decided to throw them all in the same pot.

First, the Groovy implementation:

class BubbleSort {

    static void main(args) {
        def array = [4,5,1,9,4,2]
        bubbleSort(array)
        System.out.println(array)
    }

    private static void bubbleSort(array){
        array.each {
            for(i in 0..(array.size()-2)){
                if(array[i] > array[i+1]){
                    swap(array,i)
                }
            }
        }
    }

    private static void swap(array, int idx){
        final int next = idx +1
        final int tmp = array[idx];
        array[idx] = array[next];
        array[next] = tmp;
    }
}

Next the Java implementation:

public class BubbleSort {

    public static void main(final String[] args) {
        final int[] array = {4,5,1,9,4,2};
        bubbleSort(array);
        System.out.println(Arrays.toString(array));
    }

    private static void bubbleSort(final int[] array){
        for(final int x : array){
            for(int i=0; i<array.length-1; i++){
                if(array[i] > array[i+1]) swap(array,i);
            }
        }
    }

    private static void swap(final int[] array, final int idx){
        final int next = idx + 1;
        final int tmp = array[idx];
        array[idx] = array[next];
        array[next] = tmp;
    }
}

Again you will notice that there is not much difference between Java and Groovy other than some helper constructs. Now, that’s not to say that there are not hidden groovy tricks that could not make this better… I am not a groovy expert… yet. I am also not going to say that this is the best way to do a bubble sort, there may be more efficient ways to do the algorithm.

I was working on a Ruby implementation; however, I ran into some difficulties so that will have to wait for a later posting.

These are not meant to be production-ready implementations, in fact, I would suggest not writing your own implementation and simply using Arrays.sort() with a good Comparator.

No votes yet