zoukankan      html  css  js  c++  java
  • 【排序算法】05选择排序

    接上文:【排序算法】04快速排序

    选择排序的思路:共需要进行length-1次选择,每次选择要找到选择范围内最小记录的位置, 将最小记录与选择范围内的第一个记录互换位置。

    向工具类ArraySorterUtils中添加选择排序的实现,代码如下:

     1 package org.liws1.sort;
     2 
     3 import java.util.Arrays;
     4 import java.util.Comparator;
     5 
     6 /**
     7  * 数组的排序,这里统一做升序排序
     8  */
     9 public class ArraySorterUtils {
    10     
    11     
    12     private static <T> void swap(T[] datas, int i, int j) {
    13         if (i == j) return;
    14         T temp = datas[i];
    15         datas[i] = datas[j];
    16         datas[j] = temp;
    17     }
    18     
    19     public static class InsertSorter implements IArraySorter {
    20 
    21         @Override public <T extends Comparable<T>> void sort(T[] list) {
    22             for (int i = 0; i < list.length - 1; i++) {
    23                 // 1、找到选择范围内最小记录的位置
    24                 int minIndex = i; 
    25                 for (int j = i + 1; j <= list.length - 1; j++) {
    26                     if (list[j].compareTo(list[minIndex]) < 0) {
    27                         minIndex = j;
    28                     }
    29                 }
    30                 // 2、互换选择范围内最小记录与第一个记录的位置
    31                 swap(list, i, minIndex);
    32             }
    33         }
    34 
    35         @Override public <T> void sort(T[] list, Comparator<T> comp) {
    36             // 忽略实现,跟sort(T[] list)没差
    37         }
    38         
    39     }
    40 
    41 }

    测试代码如下:

     1 package org.liws1.sort;
     2 
     3 import java.util.Arrays;
     4 import org.junit.Test;
     5 
     6 public class _Test {
     7 
     8     private Integer[] datas = { 30, 1, 29, 2, 28, 3, 27, 4, 26, 5, 25, 6, 24, 7,
     9             23, 8, 22, 9, 21, 10, 20, 19, 15, 18, 12, 17, 11, 16, 14, 13 };
    10 
    11     @Test public void testSimpleSelect(){
    12         new ArraySorterUtils.InsertSorter().sort(datas);
    13         System.out.println(Arrays.toString(datas));
    14     } // out:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
    15 }

  • 相关阅读:
    【luogu】 P1433 吃奶酪
    【noip 2016】 组合数问题(problem)
    【清北学堂】 死亡(death)
    【noip 2004】 合并果子
    微信小程序:每个邮箱仅能申请一个小程序
    Babel-polyfill 的作用
    react.js中模拟事件总线,子组件调用父组件时,发挥作用
    多行文本溢出显示省略号(…) text-overflow: ellipsis ------------- webkit-line-clamp 多行文字溢出...
    es6-class
    ES6--promise
  • 原文地址:https://www.cnblogs.com/apeway/p/10817428.html
Copyright © 2011-2022 走看看