【发布时间】:2018-04-29 20:40:39
【问题描述】:
如何修改我的整数冒泡排序代码,以便我也可以将其重新用于字符串?或者我是否需要创建一个全新的类来专门对字符串进行排序。谢谢!
主类:
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);
}
}
排序类:
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;
}
}
}
}
}
【问题讨论】:
-
google 'Java generics',或者,传递类型 'Comparable' 或类似的
-
看看它是如何完成的,例如
TreeSet。 (泛型 + 比较器)
标签: java string class sorting bubble-sort