package com.test;
import java.util.Arrays;
import java.util.Comparator;
public class BubbleSort {
private BubbleSort() {
}
// test
public static void main(String[] args) {
Integer[] list1 = new Integer[]{1, 5, 2, 4, 5, 6, 9, 10, 58, 32, 16, 3, -1, 8};
sort(list1, new Comparator<Integer>() {
@Override
public int compare(Integer t1, Integer t2) {
if (t1 > t2) return 1;
else if (t1 == t2) return 0;
else return -1;
}
});
System.out.println(Arrays.toString(list1));
Integer[] list2 = new Integer[] {1, 5, 2, 4, 5, 6, 9, 10, 58, 32, 16, 3, -1, 8};
sort(list2);
System.out.println(Arrays.toString(list2));
}
//sort with Comparator
public static <T> void sort(T[] list, Comparator<T> comparator) {
boolean swap = true; // reduce sort time under some situation
for (int i = 0, len = list.length; i < len - 1 && swap == true; i++) {
swap = false;//if swap is false after inner loop, then the list is completely sorted
for (int j = 0; j < len - i - 1; j++) {
if (comparator.compare(list[j], list[j + 1]) > 0) {
T temp = list[j];
list[j] = list[j + 1];
list[j+1] = temp;
swap = true;
}
}
}
}
// sort Comparable list
public static <T extends Comparable<T>> void sort(T[] list) {
boolean swap = true;// reduce sort time under some situation
for (int i = 0, len = list.length; i < len - 1 && swap == true; i++) {
swap = false;//if swap is false after inner loop, then the list is completely sorted
for (int j = 0; j < len - i - 1; j++) {
if (list[j].compareTo( list[j+1]) > 0) {
T temp = list[j];
list[j] = list[j + 1];
list[j+1] = temp;
swap = true;
}
}
}
}
}
冒泡排序(加速)
最新推荐文章于 2024-05-30 21:55:40 发布