Skip to content

Commit dfe0cb5

Browse files
committed
冒泡排序
1 parent a17ee51 commit dfe0cb5

File tree

2 files changed

+80
-2
lines changed

2 files changed

+80
-2
lines changed

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,11 @@
8787

8888
### 排序
8989

90-
- [快速排序][quicksort]
90+
- [冒泡排序][bubble-sort]
91+
- [快速排序][quick-sort]
9192

92-
[quicksort]: ./src/com/fantasy/algorithm/sort/QuickSort.java
93+
[bubble-sort]: ./src/com/fantasy/algorithm/sort/BubbleSort.java
94+
[quick-sort]: ./src/com/fantasy/algorithm/sort/QuickSort.java
9395

9496
### 二分查找
9597

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package com.fantasy.algorithm.sort;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* 冒泡排序,稳定算法</br>
7+
* </br>
8+
* 在最佳情况下,时间复杂度为 O(n)</br>
9+
* </br>
10+
* 在最差情况下,时间复杂度为 O(n^2)</br>
11+
* </br>
12+
* 在平均情况下,时间复杂度为 O(n^2)</br>
13+
* </br>
14+
* 空间复杂度为 O(1)
15+
*
16+
* <pre>
17+
* author : Fantasy
18+
* version : 1.0, 2020-08-29
19+
* since : 1.0, 2020-08-29
20+
* </pre>
21+
*/
22+
public class BubbleSort {
23+
24+
public static void main(String[] args) {
25+
int[] arr = new int[] { 4, 5, 6, 3, 2, 1 };
26+
System.out.println("before : " + Arrays.toString(arr));
27+
bubbleSort(arr);
28+
System.out.println("after : " + Arrays.toString(arr));
29+
}
30+
31+
public static void bubbleSort(int[] arr) {
32+
int length = arr.length;
33+
for (int i = 0; i < length; i++) {
34+
for (int j = 0; j < length - 1 - i; j++) {
35+
if (arr[j] > arr[j + 1]) {
36+
int temp = arr[j];
37+
arr[j] = arr[j + 1];
38+
arr[j + 1] = temp;
39+
}
40+
}
41+
}
42+
}
43+
44+
/**
45+
* 优化的冒泡排序</br>
46+
* </br>
47+
* 1.使用unsortedBorder记录无序区的最后一个,减少比较的次数。</br>
48+
* </br>
49+
* 2.使用isSorted来标记某一次遍历是否全部有序,有则直接跳出,减少比较的次数。
50+
*
51+
* @param arr 数组
52+
*/
53+
public static void bubbleSort2(int[] arr) {
54+
int length = arr.length;
55+
boolean isSorted = true;
56+
int lastExchangeIndex = arr.length - 1; // 用于记录最后一个比较交换的位置
57+
int unsortedBorder = lastExchangeIndex; // 记录无序区的最后一个
58+
for (int i = 0; i < length; i++) {
59+
isSorted = true; // 记录这一次遍历是否是全部有序的,有序的话则不用再比较,直接跳出
60+
for (int j = 0; j < unsortedBorder; j++) {
61+
if (arr[j + 1] < arr[j]) {
62+
int temp = arr[j];
63+
arr[j] = arr[j + 1];
64+
arr[j + 1] = temp;
65+
isSorted = false; // 有交换代表这一次遍历不是全部有序
66+
lastExchangeIndex = j; // 更新无序区的边界
67+
}
68+
}
69+
if (isSorted) {
70+
break;
71+
}
72+
unsortedBorder = lastExchangeIndex;
73+
}
74+
}
75+
76+
}

0 commit comments

Comments
 (0)