排序算法 -- 选择排序
选择排序
从序列的第一位开始,找到最小(大)值,把该值与第一位上的值交换,接着从第二个位置开始重复此动作。
效率不高,容易实现。
/** * SelectionSort.java * * @author xieyan * @date 2013/06/20 * @version 1.0 */ package sort; /** * SelectionSort.java */ public class SelectionSort { /* * 选择排序 * 从序列的第一位开始,找到最小(大)值,把该值与第一位上的值交换,接着从第二个位置开始重复此动作。 * * 效率不高,容易实现 */ /** * selectionSortAsc * * <PRE> * 升序 * </PRE> * * @param arr */ public static int[] selectionSortAsc(int[] arr) { int min = 0; int minLocal = 0; for(int i = 0; i < arr.length; i++) { min = arr[i]; minLocal = i; for(int j = i + 1; j < arr.length; j++) { if(min > arr[j]) { min = arr[j]; minLocal = j; } } arr[minLocal] = arr[i]; arr[i] = min; } return arr; } /** * selectionSortDesc * * <PRE> * 降序 * </PRE> * * @param arr */ public static int[] selectionSortDesc(int[] arr) { int min = 0; int minLocal = 0; for(int i = 0; i < arr.length; i++) { min = arr[i]; minLocal = i; for(int j = i + 1; j < arr.length; j++) { if(min < arr[j]) { min = arr[j]; minLocal = j; } } arr[minLocal] = arr[i]; arr[i] = min; } return arr; } public static void main(String[] args) { int[] a = new int[] { 5, 7, 8, 3, 4, 2, 9, 1, 6 }; int[] b = selectionSortAsc(a); for (int i = 0; i < b.length; i++) { System.out.println(b[i]); } b = selectionSortDesc(a); for (int i = 0; i < b.length; i++) { System.out.println(b[i]); } } }
相关推荐
湾区人工智能 2020-11-20
Pokemogo 2020-11-16
baijingjing 2020-11-16
baijingjing 2020-11-15
Site 2020-11-07
lwnylslwnyls 2020-11-06
justaipanda 2020-11-05
MachineIntellect 2020-11-02
xueyuediana 2020-10-30
GeraldJones 2020-10-30
Tips 2020-10-29
baijingjing 2020-10-28
baijingjing 2020-10-27
硕鼠 2020-10-26
playoffs 2020-10-26
scuyxi 2020-10-25
playoffs 2020-10-25
yise001 2020-10-23