经典排序算法之选择算法的使用 Java实例代码展示

乱世小熊 2021-08-17 11:41:24 浏览数 (1242)
反馈

一、选择排序

选择排序就是在每一次遍历过程中将数组中值最小的排到当前的第一位。

总共需要(数组长度-1)次遍历,在每次遍历中假定第一位索引的值为最小值,然后与下一个值对比,如果最小索引所在值大于其他值就将小的那一个索引当作最小值索引,接着继续对比最小索引所在值与下一个索引的值,重复此操作,最终就会在此次遍历中得到最小值及其索引,将最小值与第一位的值进行交换,这样就将最小值放到了数组开头,完成本次遍历。

选择排序的时间复杂度为O(N^2)

选择排序

二、代码实现

package com.example.algorithmdemo.sortingAlgorithm;

/**
 * 选择排序
 */
public class SelectionSort {

    /**
     * 数组排序
     * @param a
     */
    public static void sort(Comparable[] a){
        for(int i = 0;i<a.length-1;i++){
            //假设本次遍历,最小值的索引为i
            int minIndex = i;
            for(int j = i + 1;j < a.length;j++){
                if(greater(a[minIndex],a[j])){
                    //更换最小值索引
                    minIndex = j;
                }
            }
            //交换i索引和minIndex索引的值
            exchange(a,i,minIndex);
        }
    }

    /**
     * 判断参数a是否比参数b大
     * 返回true/false
     * @param a
     * @param b
     * @return
     */
    private static boolean greater(Comparable a,Comparable b){
        return a.compareTo(b)>0;
    }

    /**
     * 数组元素i和j交换位置
     * @param a
     * @param i
     * @param j
     */
    private static void exchange(Comparable[] a,int i,int j){
        Comparable temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

三、测试

package com.example.algorithmdemo.test;

import com.example.algorithmdemo.sortingAlgorithm.SelectionSort;

import java.util.Arrays;

public class SelectionTest {
    public static void main(String[] args) {
        Integer[] a = {3,2,6,8,1,4,5,7};
        SelectionSort.sort(a);
        System.out.println(Arrays.toString(a));
    }
}

在这里插入图片描述

以上就是关于Java经典排序算法之选择排序算法的详细内容,想要了解更多关于Java经典排序算法的内容,请多多关注W3Cschool


0 人点赞