Skip to content

Commit 08c5abb

Browse files
committed
选择排序
1 parent e1a7f28 commit 08c5abb

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,11 +107,13 @@
107107

108108
- [插入排序][insertion-sort]
109109
- [希尔排序][shell-sort]
110+
- [选择排序][selection-sort]
110111
- [冒泡排序][bubble-sort]
111112
- [快速排序][quick-sort]
112113

113114
[insertion-sort]: ./src/com/fantasy/algorithm/sort/InsertionSort.java
114-
[shell-sort]: ./src/com/fantasy/algorithm/sort/InsertionSort.java
115+
[shell-sort]: ./src/com/fantasy/algorithm/sort/ShellSort.java
116+
[selection-sort]: ./src/com/fantasy/algorithm/sort/SelectionSort.java
115117
[bubble-sort]: ./src/com/fantasy/algorithm/sort/BubbleSort.java
116118
[quick-sort]: ./src/com/fantasy/algorithm/sort/QuickSort.java
117119

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.fantasy.algorithm.sort;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* 选择排序,稳定算法</br>
7+
* </br>
8+
* 选择排序每次会从未排序区间中找到最小的元素,将其放到已排序区间的末尾。</br>
9+
* </br>
10+
* 在最佳情况下,时间复杂度为 O(n^2)</br>
11+
* </br>
12+
* 在最差情况下,时间复杂度为 O(n^2)</br>
13+
* </br>
14+
* 在平均情况下,时间复杂度为 O(n^2)</br>
15+
* </br>
16+
* 空间复杂度为 O(1)
17+
*
18+
* <pre>
19+
* author : Fantasy
20+
* version : 1.0, 2020-09-02
21+
* since : 1.0, 2020-09-02
22+
* </pre>
23+
*/
24+
public class SelectionSort {
25+
26+
public static void main(String[] args) {
27+
int[] arr = new int[] { 4, 5, 6, 1, 3, 2 };
28+
System.out.println("before : " + Arrays.toString(arr));
29+
selectionSort(arr);
30+
System.out.println("after : " + Arrays.toString(arr));
31+
}
32+
33+
public static void selectionSort(int[] arr) {
34+
int length = arr.length;
35+
int indexMin;
36+
for (int i = 0; i < length - 1; i++) {
37+
indexMin = i;
38+
for (int j = i + 1; j < length; j++) {
39+
if (arr[j] < arr[indexMin]) {
40+
indexMin = j;
41+
}
42+
}
43+
if (indexMin != i) {
44+
int temp = arr[indexMin];
45+
arr[indexMin] = arr[i];
46+
arr[i] = temp;
47+
}
48+
}
49+
}
50+
51+
}

0 commit comments

Comments
 (0)