选择排序算法的Java实现

八大排序算法

选择排序算法

package com.test.algorithm;

import java.util.Arrays;

/**
 * @author : sangskf
 * @package : com.test.algorithm.SelectSort
 * @date : 2019/5/28 12:30
 * @description : 选择排序
 */
public class SelectSort {

    public static void main(String[] args) {
        int[] array = new int[]{5, 2, 8, 4, 22, 31, 0, 1, 9};
        System.out.println("排序前:");
        System.out.println(Arrays.toString(array));
        System.out.println("----------------------------------");
        System.out.println("排序中:");
        selectSort(array);
        System.out.println("----------------------------------");
        System.out.println("排序后:");
        System.out.println(Arrays.toString(array));
    }

    public static void selectSort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            for (int j = i; j < array.length; j++) {
                if (array[i] > array[j]) {
                    swap(array, i, j);
                }
            }
        }
    }

    //交换元素的位置
    public static void swap(int[] array, int left, int right) {
        int temp = array[left];
        array[left] = array[right];
        array[right] = temp;
        System.out.println(Arrays.toString(array));
    }
    
}

运行结果

排序前:
[5, 2, 8, 4, 22, 31, 0, 1, 9]
----------------------------------
排序中:
[2, 5, 8, 4, 22, 31, 0, 1, 9]
[0, 5, 8, 4, 22, 31, 2, 1, 9]
[0, 4, 8, 5, 22, 31, 2, 1, 9]
[0, 2, 8, 5, 22, 31, 4, 1, 9]
[0, 1, 8, 5, 22, 31, 4, 2, 9]
[0, 1, 5, 8, 22, 31, 4, 2, 9]
[0, 1, 4, 8, 22, 31, 5, 2, 9]
[0, 1, 2, 8, 22, 31, 5, 4, 9]
[0, 1, 2, 5, 22, 31, 8, 4, 9]
[0, 1, 2, 4, 22, 31, 8, 5, 9]
[0, 1, 2, 4, 8, 31, 22, 5, 9]
[0, 1, 2, 4, 5, 31, 22, 8, 9]
[0, 1, 2, 4, 5, 22, 31, 8, 9]
[0, 1, 2, 4, 5, 8, 31, 22, 9]
[0, 1, 2, 4, 5, 8, 22, 31, 9]
[0, 1, 2, 4, 5, 8, 9, 31, 22]
[0, 1, 2, 4, 5, 8, 9, 22, 31]
----------------------------------
排序后:
[0, 1, 2, 4, 5, 8, 9, 22, 31]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值