标签:
1、内置类:
a)整数、小数Integer,Float,Double直接比较基本数据类型的大小
b)字符:比较unicode码之差
c)字符串:如果其中一个是另外一个起始开始的子串,返回长度之差,否则返回第一个不相等的unicode码之差
d)java.util.Date:根据日期的长整形数比较
字符串排序:
import java.util.Arrays; public class Demo02 { public static void main(String[] args) { String[] arr = {"a","abc","def","abcd"}; boolean sorted = true; for (int j = 0; j<arr.length-1; j++){ //趟数 sorted = true; //假定有序 System.out.println("第" + (j+1) +"趟"); for (int i=0; i<arr.length-1-j; i++){ //比较次数 System.out.print("第" + (i+1) + "次"); if (((Comparable)arr[i]).compareTo(arr[i+1]) > 0){ String temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; sorted = false; //无序 } System.out.println(Arrays.toString(arr)); } if (sorted){ //如果有序,减少趟数 break; } } System.out.println(Arrays.toString(arr)); } }
日期排序:
import java.util.Arrays; import java.util.Date; public class Demo03 { public static void main(String[] args) { Date[] arr = new Date[3]; arr[0] = new Date(); arr[1] = new Date(System.currentTimeMillis() - 1000*60*60); arr[2] = new Date(System.currentTimeMillis() + 1000*60*60); boolean sorted = true; for (int j = 0; j<arr.length-1; j++){ //趟数 sorted = true; //假定有序 System.out.println("第" + (j+1) +"趟"); for (int i=0; i<arr.length-1-j; i++){ //比较次数 System.out.print("第" + (i+1) + "次"); if (((Comparable)arr[i]).compareTo(arr[i+1]) > 0){ Date temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; sorted = false; //无序 } System.out.println(Arrays.toString(arr)); } if (sorted){ //如果有序,减少趟数 break; } } System.out.println(Arrays.toString(arr)); } }
容器排序:
import java.util.Arrays; import java.util.List; public class Utils { //List排序 public static <T extends Comparable<T>> void sort(List<T> list){ Object[] arr = list.toArray(); sort(arr); for (int i=0; i<arr.length - 1; i++){ list.set(i, (T)arr[i]); } } /** * 数组的排序 (降序) * @param arr */ public static void sort(Object[] arr){ //从大到小排序 降序 boolean sorted= true; int len =arr.length; for(int j=0;j<len-1;j++){ //趟数 sorted =true; //假定有序 for(int i=0;i<len-1-j;i++){ //次数 if(((Comparable)arr[i]).compareTo(arr[i+1])<0){ Object temp = arr[i]; arr[i] =arr[i+1]; arr[i+1] =temp; sorted =false; //假定失败 } } if(sorted){ //减少趟数 break; } } } //数组排序使用泛型 public static <T extends Comparable<T>> void sort(T[] arr){ boolean sorted = true; for (int j = 0; j<arr.length-1; j++){ //趟数 sorted = true; //假定有序 System.out.println("第" + (j+1) +"趟"); for (int i=0; i<arr.length-1-j; i++){ //比较次数 System.out.print("第" + (i+1) + "次"); if (((Comparable)arr[i]).compareTo(arr[i+1]) > 0){ T temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; sorted = false; //无序 } System.out.println(Arrays.toString(arr)); } if (sorted){ //如果有序,减少趟数 break; } } } }
标签:
原文地址:http://www.cnblogs.com/lele0609/p/4487231.html