3

How do I amend my code for bubble sorting integers so I can re-use it for strings too? Or do I need to create a completely new class for sorting strings exclusively. Thanks!

MAIN CLASS:

public class BubbleSortTest {

    public static void main(String[] args) {
        Integer[] integers = {25, 15, 45, 5, 40, 50, 10, 20, 35, 30};
        ArrayUtility.display(integers);
        BubbleSort.sort(integers);
        ArrayUtility.display(integers);

        String[] strings = {"def", "efg", "bcd", "abc", "fgh", "cde", null};
        ArrayUtility.display(strings);
        BubbleSort.sort(strings);
        ArrayUtility.display(strings);
    }
}

SORT CLASS:

public class BubbleSort {

    public static void sort(Integer[] numbers) {
        Integer temp;

        for (Integer i = 0; i < numbers.length; i++) {
            for (Integer j = 1; j < (numbers.length) - i; j++) {
                if (numbers[j - 1] > numbers[j]) {

                    //SWAPPING ELEMENTS
                    temp = numbers[j - 1];
                    numbers[j - 1] = numbers[j];
                    numbers[j] = temp;
                }
            }
        }
    }
}
2
  • 4
    google 'Java generics', or, pass type 'Comparable' or similar Commented Nov 16, 2017 at 10:38
  • Look at how it's done in e.g. TreeSet. (Generics + Comparator) Commented Nov 16, 2017 at 10:54

1 Answer 1

1

You can use Generic Types:

Something like this could be valid:

public static <E extends Comparable<E>> void bubbleSort(E[] unsorted) {
        for(int iter =1; iter< unsorted.length; iter++){
            for(int inner = 0; inner < (unsorted.length - iter); inner ++){
                if(unsorted[inner].compareTo(unsorted[inner+1]) > 0){
                    E tmp = unsorted[inner];
                    unsorted[inner] = unsorted[inner + 1];
                    unsorted[inner + 1] = tmp;
                }                
            }
        }
    }

What this means is, the method works with an array of any type, as long as it implements Comparable. Whatever type that is, will be used as E throughout the method. Since the compiler knows that E is a Comparable, the compiler knows that objects of this type have .compareTo(...).

Sign up to request clarification or add additional context in comments.

3 Comments

<E extends Comparable<E>> and the cast is not needed and all safe.
I took the liberty of editing to use what @JoopEggen correctly suggested.
Very good answer, but I wouldn't call the argument 'unsorted' because it doesn't stay unsorted for long.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.