基本思想:
从前往后循环比较,每次比较两个值,较大的值往后移,一轮比较后获得一个最大值,刚好交换到了最后;然后再进行下一轮比较,此时比较的个数为n-1,因为已经确定了最后一个值是最大值,可以减少比较次数。
代码实现:
时间复杂度O(n²)
基础版
public static void sort(int[] arr) {
int temp;
for (int i = 0; i<arr.length-1; i++) {
for (int j = 0; j < arr.length - 1-i; j++) {
//如果前面的数比后面的数大,就交换
if (arr[j] > arr[j + 1]) {
temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
}
better
比如有这样一种情况
[10,1,2,3,4,5,6]
他难道经过一轮循环后[1,2,3,4,5,6,10]还要再继续循环吗?浪费时间
我们需要给一个标志,判断如果一次循环中,一次位置交换都没有发生,那么说明这个数组已经排好序了,直接跳出,结束程序。
public static void betterSort(int[] arr) {
int temp;
boolean flag = false;
for (int i = 0; i<arr.length-1; i++) {
for (int j = 0; j < arr.length - 1-i; j++) {
//如果前面的数比后面的数大,就交换,并把flag置为true
if (arr[j] > arr[j + 1]) {
flag = true;
temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
if (!flag){//在一次排序中,如果没有发生交换,说明已经排序好了,直接跳出就行
break;
}else {
flag = false;
}
}
}
GitHub上放了源码,包含测试
https://github.com/FanZejie/dataStructure1/blob/master/maopao/src/MaoPaoSort.java