Skip to content

Commit a68f3a8

Browse files
committed
第二次提交 选择排序 v1 for 简单排序v1
1 parent 5267ed5 commit a68f3a8

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.oslee.algorithm.sort;
2+
3+
4+
public class Selection {
5+
6+
/*
7+
对数组a中的元素进行排序
8+
*/
9+
public static void sort(Comparable[] a){
10+
for (int i = 0; i < a.length - 1; i++) {
11+
// 定义一个变量 记录最小元素所在的索引 默认为参与选择排序的第一个元素所在的位置
12+
int minIndex = i;
13+
for (int j = i + 1; j < a.length; j++) {
14+
// 比较最小索引minIndex处的值和j索引处的值
15+
if(greater(a[minIndex], a[j])){
16+
minIndex = j;
17+
}
18+
}
19+
// 交换最小元素所在索引minIndex处的值和索引i的位置
20+
exch(a, i, minIndex);
21+
}
22+
}
23+
24+
/*
25+
判断v是否大于w
26+
*/
27+
private static boolean greater(Comparable v, Comparable w){
28+
return v.compareTo(w) > 0;
29+
}
30+
31+
/*
32+
交换a数组中, 索引i和索引j处的值
33+
*/
34+
private static void exch(Comparable[] a, int i, int j){
35+
Comparable temp;
36+
temp = a[i];
37+
a[i] = a[j];
38+
a[j] = temp;
39+
}
40+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.oslee.algorithm.test;
2+
3+
4+
import com.oslee.algorithm.sort.Selection;
5+
6+
import java.util.Arrays;
7+
8+
public class SelectionTest {
9+
public static void main(String[] args) {
10+
// 原始数据
11+
Integer[] a = {4, 6, 8, 7, 9, 2, 10, 1};
12+
Selection.sort(a);
13+
System.out.println(Arrays.toString(a));
14+
}
15+
}

0 commit comments

Comments
 (0)