选择排序,用java实现

一.介绍

选择排序法先找到数列中最小的数,然后将它和第一个元素交换。接下来,在剩下的数中找到最小数,将它和第二个元素交换,依此类推,直到数列中仅剩一个数为止。

二.代码

package com.zhuo.base;

import java.lang.reflect.Array;
import java.util.Arrays;

public class SelectionSort {
     
    public static void main(String[] args) {
     
        double[] list = {
     1,9,4.5,6.6,5.7,-4.5};
        selectionSort(list);
        System.out.println(Arrays.toString(list));
    }
    public static void selectionSort(double[] list) {
     
        for (int i = 0; i < list.length - 1; i++) {
     
            double currentMin = list[i];
            int currentMinIndex = i;
            for (int j = i + 1;j < list.length;j++) {
     
                if(currentMin > list[j]) {
     
                    currentMin = list[j];
                    currentMinIndex = j;
                }
            }
            if (currentMinIndex != i)
            {
     
                list[currentMinIndex] = list[i];
                list[i] = currentMin;
            }
        }
    }
}

三.结果实现

[-4.5, 1.0, 4.5, 5.7, 6.6, 9.0]

Process finished with exit code 0

你可能感兴趣的:(JavaSE,javase)