Skip to content

Commit f6de6f1

Browse files
committed
SelectionSortTest__选择排序
1 parent 8a335c5 commit f6de6f1

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package com.cpucode.sort.selection;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* 选择排序
7+
* 选择排序算法的实现思路有点类似插入排序,也分已排序区间和未排序区间。
8+
* 但是选择排序每次会从未排序区间中找到最小的元素,将其放到已排序区间的末尾。
9+
*
10+
* 算法分析
11+
* 空间复杂度 O(1),时间复杂度 O(n²)。
12+
*
13+
* 那选择排序是稳定的排序算法吗?
14+
*
15+
* 答案是否定的,选择排序是一种不稳定的排序算法。
16+
* 选择排序每次都要找剩余未排序元素中的最小值,并和前面的元素交换位置,这样破坏了稳定性。
17+
*
18+
* 比如 5,8,5,2,9 这样一组数据,使用选择排序算法来排序的话,
19+
* 第一次找到最小元素 2,与第一个 5 交换位置,那第一个 5 和中间的 5 顺序就变了,
20+
* 所以就不稳定了。正是因此,相对于冒泡排序和插入排序,选择排序就稍微逊色了。
21+
*
22+
* @author : cpucode
23+
* @date : 2021/5/13
24+
* @time : 21:22
25+
* @github : https://github.com/CPU-Code
26+
* @csdn : https://blog.csdn.net/qq_44226094
27+
*/
28+
public class SelectionSortTest {
29+
public static void main(String[] args) {
30+
int[] nums = {1, 2, 7, 9, 5, 8};
31+
selectionSort(nums);
32+
33+
System.out.println(Arrays.toString(nums));
34+
}
35+
36+
private static void selectionSort(int[] nums) {
37+
for (int i = 0, n = nums.length; i < n - 1; i++) {
38+
int minIndex = i;
39+
40+
for (int j = i; j < n; j++) {
41+
if (nums[j] < nums[minIndex]){
42+
minIndex = j;
43+
}
44+
}
45+
46+
swap(nums, minIndex, i);
47+
}
48+
}
49+
50+
private static void swap(int[] nums, int i, int j) {
51+
int t = nums[i];
52+
nums[i] = nums[j];
53+
nums[j] = t;
54+
}
55+
}

0 commit comments

Comments
 (0)