Skip to content

Commit 7d9a891

Browse files
author
chenweijie
committed
选择排序
1 parent ce0384e commit 7d9a891

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package com.chen.algorithm.sort;
2+
3+
/**
4+
*
5+
* 选择排序是每一次从待排序的数据元素中选出最小的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。
6+
  分为三步:
7+
  ①、从待排序序列中,找到关键字最小的元素
8+
  ②、如果最小元素不是待排序序列的第一个元素,将其和第一个元素互换
9+
  ③、从余下的 N - 1 个元素中,找出关键字最小的元素,重复(1)、(2)步,直到排序结束
10+
*
11+
*
12+
* @author : chen weijie
13+
* @Date: 2019-02-28 12:25 AM
14+
*/
15+
public class ChoiceSort {
16+
17+
18+
public static int[] sort(int[] array) {
19+
20+
//总共进行n-1轮比较
21+
for (int i = 0; i < array.length - 1; i++) {
22+
int min = i;
23+
//每轮需要比较的次数
24+
for (int j = i + 1; j < array.length; j++) {
25+
if (array[j] < array[min]) {
26+
//记录目前能找到的最小值元素的下标
27+
min = j;
28+
}
29+
}
30+
31+
if (i != min) {
32+
int temp = array[i];
33+
array[i] = array[min];
34+
array[min] = temp;
35+
}
36+
//第 i轮排序的结果为
37+
System.out.print("第" + (i + 1) + "轮排序后的结果为:");
38+
display(array);
39+
}
40+
41+
return array;
42+
}
43+
44+
45+
//遍历显示数组
46+
public static void display(int[] array) {
47+
for (int i = 0; i < array.length; i++) {
48+
System.out.print(array[i] + " ");
49+
}
50+
System.out.println();
51+
}
52+
53+
public static void main(String[] args) {
54+
55+
int[] array = {4, 2, 8, 9, 5, 7, 6, 1, 3};
56+
//未排序数组顺序为
57+
System.out.println("未排序数组顺序为:");
58+
display(array);
59+
System.out.println("-----------------------");
60+
array = sort(array);
61+
System.out.println("-----------------------");
62+
System.out.println("经过选择排序后的数组顺序为:");
63+
display(array);
64+
}
65+
66+
67+
68+
69+
}

0 commit comments

Comments
 (0)