list和數組排序(冒泡)
阿新 • • 發佈:2018-11-19
nds sys style list compare arraylist () 改變 oid
1 package cn.test.bubble; 2 3 import java.util.ArrayList; 4 import java.util.Arrays; 5 import java.util.List; 6 7 /** 8 * @author weianlai 9 * @date 2018/11/2018/11/18 18:42 10 */ 11 public class BubbleSort { 12 13 public static void main(String[] args) { 14 // Integer[] arr = {1,8,3,5,9};15 // String[] arr2 = {"f","a","y"}; 16 // arraySort(arr2); 17 // System.out.println(Arrays.toString(arr2)); 18 19 List<String> list = new ArrayList<String>(); 20 list.add("f"); 21 list.add("a"); 22 list.add("y"); 23 listSort(list);24 System.out.println(list); 25 } 26 27 public static <T extends Comparable<T>> void listSort(List<T> list) { 28 //將list轉成數組 29 Object[] arr = list.toArray(); 30 arraySort(arr); 31 //改變list的值 32 for (int i = 0; i < arr.length; i++) {33 list.set(i, (T) arr[i]); 34 } 35 } 36 37 /** 38 * 數組冒泡排序(泛型方法) 39 * @param arr 40 */ 41 public static <T> void arraySort(T[] arr) { 42 int len = arr.length; 43 boolean sorted = true; 44 for (int j = 0; j < len-1; j++) { 45 //假定有序 46 sorted = true; 47 for (int i = 0; i < len-1-j; i++) { 48 if (((Comparable) arr[i]).compareTo(arr[i+1]) > 0) { 49 T temp = arr[i]; 50 arr[i] = arr[i+1]; 51 arr[i+1] = temp; 52 sorted = false; 53 } 54 } 55 if (sorted) { 56 break; 57 } 58 } 59 } 60 61 }
list和數組排序(冒泡)