package com.sort;
/*--------------
* Author:Real_Q
* Date:2021-01-06
* Time:12:29
* Description:选择排序
* {4,6,8,7,9,2,10,1};
---------------*/
public class SelectSort {
public static void selectSort(Comparable[] comparables) {
//排序次数 i
for (int i = 0; i < comparables.length - 1; i++) {
//比较遍历数组,找到最小数,记录索引 j
int min = i;
for (int j = i + 1; j < comparables.length; j++) {
if (Comparable(comparables[min], comparables[j])) {
min = j;
}
}
exchange(comparables, i, min);
}
}
//比较大小
public static boolean Comparable(Comparable comparable1, Comparable comparable2) {
return comparable1.compareTo(comparable2) > 0;
}
//交换元素
public static void exchange(Comparable[] comparable, int leftIndex, int rightIndex) {
Comparable temp;
temp = comparable[leftIndex];
comparable[leftIndex] = comparable[rightIndex];
comparable[rightIndex] = temp;
}
}
import java.util.Arrays;
import static com.sort.SelectSort.selectSort;
public class TestSelect {
public static void main(String[] args) {
Integer[] array = {4,6,8,7,9,2,10,1};
selectSort(array);
System.out.println(Arrays.toString(array));
}
}
原文:https://www.cnblogs.com/RealQ/p/14253827.html