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;
}
}
}
}
}
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(...)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.