简单选择排序
1.算法思想
找到数组中最小的数,与第一位的数交换,这样第一位就完成排序了。
找到数组中第二小的数(此过程可剔除第一位数,因为第一位已经完成排序,不会再发生改变),与第二位的数交换,第二位的数即可完成排序。
……
直到找到数组中第二大的数,与倒数第二位的数交换。
至此,数组即可全部完成排序。
2. 代码实现
package sort;
public class SelectSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = { 5, 7, 1, 4, 3, 6, 2 };
for (int item : arr) {
System.out.print(item + " ");
}
System.out.println();
selectSort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
// 简单选择排序
public static int[] selectSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
// 声明变量index记录当前数组最小的数的下标
int index = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[index]) {
// 遇到更小的数我们只需要记录其下标,最后进行1次交换即可
index = j;
}
}
if (index != i) {
int t = arr[i];
arr[i] = arr[index];
arr[index] = t;
}
}
return arr;
}
}
3. 运行结果
4. 过程分解
本次实例选择从小到大排序。
5 | 7 | 1 | 4 | 3 | 6 | 2 |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
5和7比较,index未发生改变。
5 | 7 | 1 | 4 | 3 | 6 | 2 |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
5和1比较,index记录j的值。
5 | 7 | 1 | 4 | 3 | 6 | 2 |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
5 | 7 | 1 | 4 | 3 | 6 | 2 |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
1和4比较,index未发生改变。
5 | 7 | 1 | 4 | 3 | 6 | 2 |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
1和3比较,index未发生改变。
5 | 7 | 1 | 4 | 3 | 6 | 2 |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
1和6比较,index未发生改变。
5 | 7 | 1 | 4 | 3 | 6 | 2 |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
1和2比较,index未发生改变。
交换i和index处的值。
7 | 5 | 4 | 3 | 6 | 2 | |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
至此,1已完成排序。
7 | 5 | 4 | 3 | 6 | 2 | |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
比较7和5,index记录j的值。
7 | 5 | 4 | 3 | 6 | 2 | |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
7 | 5 | 4 | 3 | 6 | 2 | |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
5和4比较,index记录j的值。
7 | 5 | 4 | 3 | 6 | 2 | |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
7 | 5 | 4 | 3 | 6 | 2 | |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
4和3比较,index记录j的值。
7 | 5 | 4 | 3 | 6 | 2 | |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
7 | 5 | 4 | 3 | 6 | 2 | |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
3和6比较,index未发生改变。
7 | 5 | 4 | 3 | 6 | 2 | |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
3和2比较,index记录j的值。
7 | 5 | 4 | 3 | 6 | 2 | |
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
交换i和index处的值。
5 | 4 | 3 | 6 | 7 | ||
---|---|---|---|---|---|---|
↑( i ) | ↑( j ) | |||||
↑( index ) |
至此,1、2已完成排序。
……
↑( i ) | ↑( j ) | |||||
↑( index ) |