/**
* 选择排序
*
* @author 小流慢影
* @date 2023年3月11日
*/
public class SelectionSortDemo {
public static void main(String[] args) {
int[] array = {5, 4, 3, 1, 2, 7, 8, 6, 10, 9, 13, 12, 11};
selectionSort(array);
System.out.println(Arrays.toString(array));
}
/**
* 选择排序具体方法
* @param array 数组
*/
public static void selectionSort(int[] array) {
/*
* 选择排序是从第一个位置开始,每一轮将这个位置的数据和之后的所有数据比较,取最小(或者最大)的与其交换,——>
* -->然后下一个位置重复操作。
* firstLocation代表要与后面数据比较的位置,既然是位置,由于数组位置从0开始,——>
* ——>故最大位置为【array.length - 1】,由于firstLocation是与后面数据比较,所以只能小于最大位置,-->
* -->方便最后一次时,还能与最大位置比较一次。
*/
for (int firstLocation = 0; firstLocation < array.length - 1; firstLocation++) {
// 每一轮比较开始时,默认开始位置是最小位置
int minLocation = firstLocation;
// 比较位置从开始位置的下一个开始,到数组最大位置【array.length - 1】结束
for (int compareLocation = firstLocation + 1;
compareLocation < array.length; compareLocation++) {
// 如果比较位置比前面记录的最小位置还要小,则把比较位置记为最小位置
if (array[compareLocation] < array[minLocation]) {
minLocation = compareLocation;
}
}
/*
* 上面一轮比较下来,最小位置就出来了.然后将最小位置与第一个位置比较,如果最小位置就是第一个位置,-->
* -->则保持不变,如果比第一个位置大,则与第一个位置进行交换。
*/
if (minLocation > firstLocation) {
swap(array, minLocation, firstLocation);
}
}
}
/**
* 交换
*
* @param array 数组
* @param minLocation 最小的位置
* @param firstLocation 第一个位置
*/
public static void swap(int[] array, int minLocation, int firstLocation) {
int temp = array[minLocation];
array[minLocation] = array[firstLocation];
array[firstLocation] = temp;
}
}
Java选择排序
于 2023-03-11 22:57:11 首次发布