冒泡排序
- 一共有8大排序,冒泡排序无疑最为出名。
- 冒泡的代码还是相当简单的,两层循环,外层冒泡轮数,里层依次比较。
- 嵌套循环,算法的时间复杂度为O(n2)。
/*
外层循环循环次数 array.length - 1
内层循环,比较判断两个数大小,大的放右边
*/
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// 冒泡排序
int[] a = {9, 1, 29, 3, 44, 68, 5, 10, 6 ,67 ,1};
int count = 0;
int temp = a[0];
for (int i = 0; i < a.length - 1; i++) {
// 每一步都找出最大的值(从小到大排列)
for (int j = 0; j < a.length -i - 1; j++) {
count++;
if (a[j + 1] < a[j]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
System.out.println(Arrays.toString(a));
}
System.out.println(count);
}
}
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// 排序
int[] a = {9, 1, 29, 3, 44, 68, 5, 10};
int count = 0;
int temp = a[0];
for (int i = 0; i < a.length - 1; i++) {
// 把最小的放到最左边
for (int j = i; j < a.length - 1; j++) {
count++;
if (a[j + 1] < a[i]) {
temp = a[j + 1];
a[j + 1] = a[i];
a[i] = temp;
}
}
System.out.println(Arrays.toString(a));
}
System.out.println(count);
}
}
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// 冒泡排序优化
int[] a = {9, 1, 29, 3, 44, 68, 5, 10, 6, 67, 1};
int count = 0;
int temp = a[0];
for (int i = 0; i < a.length - 1; i++) {
boolean flag = false; //如果没有交换的话就直接跳出循环
for (int j = 0; j < a.length - i - 1; j++) {
count++;
if (a[j + 1] < a[j]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
flag = true;
}
}
if (!flag) {
break;
}
System.out.println(Arrays.toString(a));
}
System.out.println(count);
}
}