排序算法(Sorting Algorithms)
By Long Luo
1. 冒泡排序(Bubble Sort)
思路与算法:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23public static int[] bubbleSort(int[] nums) {
if (nums == null || nums.length <= 1) {
return nums;
}
int len = nums.length;
for (int i = len - 1; i >= 0; i--) {
boolean isSorted = true;
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
isSorted = false;
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
if (isSorted) {
break;
}
}
return nums;
}
复杂度分析:
- 时间复杂度:\(O(N^2)\) ,其中 \(N\) 是数组 \(\textit{nums}\) 的长度。
- 空间复杂度:\(O(1)\) 。
2. 选择排序(Select Sort)
思路与算法:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public static int[] selectSort(int[] nums) {
if (nums == null || nums.length <= 1) {
return nums;
}
int len = nums.length;
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (nums[j] < nums[i]) {
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
}
}
}
return nums;
}
复杂度分析:
- 时间复杂度:\(O(N^2)\) ,其中 \(N\) 是数组 \(\textit{nums}\) 的长度。
- 空间复杂度:\(O(1)\) 。