java基础算法之选择排序算法

        选择排序的基本思想是:在未排序的序列中找到最小(或最大)元素,存放到排序序列的起始位置,然后再从剩余未排序元素中继续寻找最小(或最大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。

package com.example.datastructures.sort;

import java.util.Arrays;

/**
 * @author maoyouhua
 * @version jdk21
 *
 *          选择排序
 *
 *          选择排序的基本思想是:在未排序的序列中找到最小(或最大)元素,存放到排序序列的起始位置,
 *          然后再从剩余未排序元素中继续寻找最小(或最大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
 */
public class SelectSort {

    /**
     *
     * @param arr   排序数组
     */
    private static void selectSort(int[] arr){
        int temp = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            temp = arr[i];
            int minIndex = min(arr, i);
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
            System.out.println("第"+ (i+1) +"次排序");
            System.out.println(Arrays.toString(arr));
        }
    }
    /**
     *      从指定下标起找出数组最小的数
     * @param arr
     * @param index
     * @return
     */
    private static int min(int[] arr, int index){
        int minIndex = index;
        for (int i = index; i < arr.length - 1; i++) {
            if (arr[minIndex] > arr[i+1]){
                minIndex = i+1;
            }
        }
        return minIndex;
    }

    /**
     *      排序效率测试
     *      花费时间是:1171毫秒
     */
    private static void efficiencyTest(){
        int capacity = 80000;
        int[] arr = new int[capacity];
        for (int i = 0; i < capacity; i++) {
            arr[i] = (int)(Math.random()  * 100 * capacity);
        }
        long start = System.currentTimeMillis();
        selectSort(arr);
        long end = System.currentTimeMillis();
        System.out.println("花费时间是:" + (end - start) + "毫秒");
    }

    /**
     *第1次排序
     * [-3, 9, -1, 7, 3, 10, 8, 3, -2]
     * 第2次排序
     * [-3, -2, -1, 7, 3, 10, 8, 3, 9]
     * 第3次排序
     * [-3, -2, -1, 7, 3, 10, 8, 3, 9]
     * 第4次排序
     * [-3, -2, -1, 3, 7, 10, 8, 3, 9]
     * 第5次排序
     * [-3, -2, -1, 3, 3, 10, 8, 7, 9]
     * 第6次排序
     * [-3, -2, -1, 3, 3, 7, 8, 10, 9]
     * 第7次排序
     * [-3, -2, -1, 3, 3, 7, 8, 10, 9]
     * 第8次排序
     * [-3, -2, -1, 3, 3, 7, 8, 9, 10]
     */
    public static void main(String[] args) {
        int[] arr = {3,9,-1,7,-3,10,8,3,-2};
        selectSort(arr);
        efficiencyTest();
    }

}

  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值