版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zzl913657644/article/details/70551269
public class BubbleSort<T extends Comparable<? super T>> {
public void sort(T[] arr) {
for (int i = arr.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (arr[j].compareTo(arr[j + 1]) > 0) {
T temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
//改进后的冒泡排序
public class BubbleSortAdvance<T extends Comparable<? super T>> {
/**
* 用n记录了最后一次交换的位置
* 减少了n到i间的重复比较
*/
public void sort(T[] arr) {
int n = arr.length;
boolean swaped = false;
for (int i = n - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (arr[j].compareTo(arr[j + 1]) > 0) {
T temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
n = j + 1;//+1是因为外层循环每次要i--
swaped = true;
}
}
i = swaped ? n : i;
swaped = false;
}
}
}