码迷,mamicode.com
首页 > 编程语言 > 详细

选择排序

时间:2021-06-13 10:59:57      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:main   append   eal   排序   class   tmp   比较   ati   swap   

  • 算法思维:从0n-1每次取一个为i, 和i后面的元素进行比较
  • int k = i;如果发现比i位置上的还小,则将该位置的角标赋值给k。
  • 最后交换i 和 k的位置;每一趟都能排好一个最小的值。
package simpleAlgorithm;


/**
 * @Author: WhaleFall541
 * @Date: 2021/4/4 16:08
 * 算法思维:从`0`到`n-1`每次取一个为`i`, 和i后面的元素进行比较
 * 令`int k = i;`如果发现比`i`位置上的还小,则将该位置的角标赋值给k。
 * 最后交换i 和 k的位置;每一趟都能排好一个最小的值。
 */
public class SelectSort {

    public static void main(String[] args) {
        int[] arr = {-1111, 20, -3, -10, 100, -255};
        selectSort(arr);

        StringBuilder sb = new StringBuilder();
        for (int i : arr)
            sb.append(i).append(" ");
        System.out.println("sb = " + sb);

    }

    //选择排序
    private static void selectSort(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            int k = i;// i是要排序的数下标
            // 跟i下标后面的每个元素比较记录下来arr[k]最小的k值
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[k] > arr[j])
                    k = j;
            }

            // 最小的arr[k] 和 当前排序位置arr[i]互换
            swap(arr, i, k);
        }
    }


    private static void swap(int[] arr, int a, int b) {
        int tmp = arr[a];
        arr[a] = arr[b];
        arr[b] = tmp;
    }

}

选择排序

标签:main   append   eal   排序   class   tmp   比较   ati   swap   

原文地址:https://www.cnblogs.com/whalefall541/p/14879378.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!