Selection sort, implemented in java

1. Introduction

The selection sort method first finds the smallest number in the sequence, and then exchanges it with the first element. Next, find the smallest number among the remaining numbers, swap it with the second element, and so on, until there is only one number left in the sequence.

2. Code

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;
            }
        }
    }
}

3. Results achieved

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

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/weixin_42768634/article/details/113709470