概述
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;
}
}
}
}
}
最后
以上就是顺心巨人为你收集整理的冒泡排序(加速)的全部内容,希望文章能够帮你解决冒泡排序(加速)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复