package com.zsx.algorithm.sort;
import java.util.Arrays;
public class SelectionSort {
public static void main(String[] args) {
int[] arr = {1, 3, 8, 4, 20, 5, 7, -1, 2, 24, 9};
System.out.println("初始数据:" + Arrays.toString(arr));
System.out.println();
SelectionSort selectionSort = new SelectionSort();
selectionSort.sort(arr);
System.out.println();
System.out.println("最终结果:" + Arrays.toString(arr));
}
public void sort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minValue = arr[i];
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < minValue) {
minValue = arr[j];
minIndex = j;
}
}
int tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
System.out.println("遍历第" + (i + 1) + "次");
System.out.print("排序过程:");
for (int j = 0; j <= i; j++) {
System.out.print(arr[j] + " ");
}
System.out.print(" ");
for (int j = i + 1; j < arr.length; j++) {
System.out.print(arr[j] + " ");
}
System.out.println();
System.out.println("结果:" + Arrays.toString(arr));
System.out.println();
}
}
}
控制台结果如下:
初始数据:[1, 3, 8, 4, 20, 5, 7, -1, 2, 24, 9]
遍历第1次
排序过程:-1 3 8 4 20 5 7 1 2 24 9
结果:[-1, 3, 8, 4, 20, 5, 7, 1, 2, 24, 9]
遍历第2次
排序过程:-1 1 8 4 20 5 7 3 2 24 9
结果:[-1, 1, 8, 4, 20, 5, 7, 3, 2, 24, 9]
遍历第3次
排序过程:-1 1 2 4 20 5 7 3 8 24 9
结果:[-1, 1, 2, 4, 20, 5, 7, 3, 8, 24, 9]
遍历第4次
排序过程:-1 1 2 3 20 5 7 4 8 24 9
结果:[-1, 1, 2, 3, 20, 5, 7, 4, 8, 24, 9]
遍历第5次
排序过程:-1 1 2 3 4 5 7 20 8 24 9
结果:[-1, 1, 2, 3, 4, 5, 7, 20, 8, 24, 9]
遍历第6次
排序过程:-1 1 2 3 4 5 7 20 8 24 9
结果:[-1, 1, 2, 3, 4, 5, 7, 20, 8, 24, 9]
遍历第7次
排序过程:-1 1 2 3 4 5 7 20 8 24 9
结果:[-1, 1, 2, 3, 4, 5, 7, 20, 8, 24, 9]
遍历第8次
排序过程:-1 1 2 3 4 5 7 8 20 24 9
结果:[-1, 1, 2, 3, 4, 5, 7, 8, 20, 24, 9]
遍历第9次
排序过程:-1 1 2 3 4 5 7 8 9 24 20
结果:[-1, 1, 2, 3, 4, 5, 7, 8, 9, 24, 20]
遍历第10次
排序过程:-1 1 2 3 4 5 7 8 9 20 24
结果:[-1, 1, 2, 3, 4, 5, 7, 8, 9, 20, 24]
最终结果:[-1, 1, 2, 3, 4, 5, 7, 8, 9, 20, 24]
Process finished with exit code 0