File tree Expand file tree Collapse file tree 1 file changed +70
-0
lines changed
Expand file tree Collapse file tree 1 file changed +70
-0
lines changed Original file line number Diff line number Diff line change 1+ package sorts ;
2+
3+ /**
4+ * 冒泡排序、插入排序、选择排序
5+ *
6+ * Author: Zheng
7+ */
8+ public class Sorts {
9+
10+ // 冒泡排序,a是数组,n表示数组大小
11+ public static void bubbleSort (int [] a , int n ) {
12+ if (n <= 1 ) return ;
13+
14+ // 提前退出标志位
15+ boolean flag = false ;
16+ for (int i = 0 ; i < n ; ++i ) {
17+ for (int j = 0 ; j < n - i - 1 ; ++j ) {
18+ if (a [j ] > a [j +1 ]) { // 交换
19+ int tmp = a [j ];
20+ a [j ] = a [j +1 ];
21+ a [j +1 ] = tmp ;
22+ // 此次冒泡有数据交换
23+ flag = true ;
24+ }
25+ }
26+ if (!flag ) break ; // 没有数据交换,提前退出
27+ }
28+ }
29+
30+ // 插入排序,a表示数组,n表示数组大小
31+ public static void insertionSort (int [] a , int n ) {
32+ if (n <= 1 ) return ;
33+
34+ for (int i = 1 ; i < n ; ++i ) {
35+ int value = a [i ];
36+ int j = i - 1 ;
37+ // 查找要插入的位置并移动数据
38+ for (; j >= 0 ; --j ) {
39+ if (a [j ] > value ) {
40+ a [j +1 ] = a [j ];
41+ } else {
42+ break ;
43+ }
44+ }
45+ a [j +1 ] = value ;
46+ }
47+ }
48+
49+ // 选择排序,a表示数组,n表示数组大小
50+ public static void selectionSort (int [] a , int n ) {
51+ if (n <= 1 ) return ;
52+ for (int i = 0 ; i < n ; ++i ) {
53+ // 查找最小值
54+ int minIndex = i ;
55+ int minValue = a [i ];
56+ for (int j = i ; j < n ; ++j ) {
57+ if (a [j ] < minValue ) {
58+ minValue = a [j ];
59+ minIndex = j ;
60+ }
61+ }
62+
63+ // 交换
64+ int tmp = a [i ];
65+ a [i ] = a [minIndex ];
66+ a [minIndex ] = tmp ;
67+ }
68+ }
69+
70+ }
You can’t perform that action at this time.
0 commit comments