
- /**
- * 选择排序
- *
- * @version 1.0
- * @date 2023/09/01 17:57:05
- */
- public class Select {
-
-
- /**
- * 升序选择排序
- *
- * @param a 待排序的数组
- * @date 2023/9/1 15:29:10
- */
- public static void sortAes(int[] a) {
- //数组长度
- int length = a.length;
- for (int i = 0; i <= length-2; i++) {
- //假设第一个元素为最小值
- int minIndex = i;
- for (int j = i+1; j <= length-1; j++) {
- //寻找最小值的下标
- if (a[minIndex] > a[j]) {
- minIndex = j;
- }
- }
- //将最小值下标对应的数据与第一个元素交换
- int minValue = a[minIndex];
- a[minIndex] = a[i];
- a[i] = minValue;
- }
- }
-
- /**
- * 降序选择排序
- *
- * @param a 待排序的数组
- * @date 2023/9/1 15:29:10
- */
- public static void sortDesc(int[] a) {
- int length = a.length;
- for (int i = 0; i <= length-2; i++) {
- //假设第一个元素是最大值
- int maxIndex = i;
- for (int j = i+1; j <= length-1; j++) {
- //寻找最大值元素的下标
- if (a[maxIndex] < a[j]) {
- maxIndex = j;
- }
- }
- //交换最大值
- int maxValue = a[maxIndex];
- a[maxIndex] = a[i];
- a[i] = maxValue;
- }
- }
- }
- public class SelectTest {
- public static void main(String[] args) {
- int[] array = {56, 88, 23, 99, 12, 34, -15, -45, 78, 67, 32};
- //升序排列
- //Select.sortAes(array);
- //降序排列
- Select.sortDesc(array);
- System.out.println(Arrays.toString(array));
- }
- }