#数据结构排序之冒泡排序
两两比较,大的往后走,小的往前走
- 时间复杂度 O(n2)
- 空间复杂度o(1);
- 稳定性:稳定
- 1 2 3 4 5
- 优化
- 用一个标志Flag实现
- 有序只排一趟序
在这里插入代码片
public class BubbleTest {
public static void BubbleSort(int[] array) {
//趟数//n-1
for (int i = 0; i < array.length; i++) {
//一趟冒泡的过程
for (int j = 0; j < array.length - 1 - i; j++) {
if (array[j + 1] < array[j]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
public static void optimizedBubbleSort(int [] array) {
if (array == null || array.length == 0) {
return ;
}
//趟数
boolean needNextSort = true;
for (int i = 0; i < array.length - 1 && needNextSort; i++) {
//一趟冒泡的过程
needNextSort = false;
for (int j = 0; j < array.length - 1 - i; j++) {
if (array[j] > array[j + 1]) {
int tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
needNextSort = true;
}
}
}
}
public static void main(String[] args) {
int [] array={10,6,8,2,3,0,10,15,29,9};
BubbleSort(array);
optimizedBubbleSort(array);
System.out.println(Arrays.toString(array));
System.out.println(Arrays.toString(array));
}
}
//测试结果
[0, 2, 3, 6, 8, 9, 10, 10, 15, 29]
[0, 2, 3, 6, 8, 9, 10, 10, 15, 29]