public class TestSort { public static <T> T[] bubbleSort(T array[]) { if (array.length < 2) { return array; } int len = array.length; for (int i = 0; i < len; i++) { for (int j = 0; j < len - i - 1; j++) { if (compareTo(array[j + 1], array[j]) > 0) { T t = array[j + 1]; array[j + 1] = array[j]; array[j] = t; } } } return array; } public static <T> int compareTo(T t1, T t2) { if (t1 instanceof Integer && t2 instanceof Integer) { Integer i1 = (Integer) t1; Integer i2 = (Integer) t2; return i1.compareTo(i2); } else if (t1 instanceof String && t2 instanceof String) { String s1 = (String) t1; String s2 = (String) t2; return s1.compareTo(s2); } return 0; } public static void main(String[] args) { String array1[] = new String[]{"a", "b", "d", "c", "g", "k"}; Integer array2[] = new Integer[]{1, 4, 6, 2, 3, 9,333,456,126,214}; array1 = bubbleSort(array1); for (String s : array1) { System.out.println(s); } array2 = bubbleSort(array2); for (Integer integer : array2) { System.out.println(integer); } } }
使用泛型实现对整型和字符串的冒泡排序
最新推荐文章于 2022-06-14 21:39:56 发布