1 /** 2 * 3 */ 4 package com.trfizeng.selectionsort; 5 6 /** 7 * @author trfizeng 内部排序 选择排序—简单选择排序(Simple Selection Sort) 8 */ 9 public class SimpleSelectionSort { 10 11 /** 12 * 每次选择一个最小记录放在前面去 13 */ 14 public static int[] simpleSelectionSort(int[] array) { 15 // 对传来的待排序数组进行合法验证 16 if (array != null && array.length != 0) { 17 for (int i = 0; i < array.length; i++) { 18 // 记录最小记录的下标 19 int k = i; 20 // 查找最小的记录 内层循环执行完将找到最小记录 21 for (int j = i + 1; j < array.length; j++) { 22 // 如果当前记录是比后面一个大的话就把后面一个下标赋给当前下标 23 if (array[k] > array[j]) { 24 k = j; 25 } 26 } 27 // 把最小记录与当前记录进行兑换 28 int temp = array[i]; 29 array[i] = array[k]; 30 array[k] = temp; 31 } 32 } 33 return array; 34 } 35 }
1 package com.trfizeng.test; 2 3 import com.trfizeng.insertionsort.StraightInsertionSort; 4 import com.trfizeng.selectionsort.SimpleSelectionSort; 5 6 /** 7 * 测试类 8 * 9 * @author trfizeng 10 * 11 */ 12 public class SortTest { 13 // 待排序数组 14 static int[] array = new int[] { 6, 1, 4, 10, 11, 8, 7, 1, 0 }; 15 16 /** 17 * 直接插入排序法测试 18 */ 19 public static void straightInsertionSortTest() { 20 System.out.print("待排序数组:[ "); 21 for (int i = 0; i < array.length; i++) { 22 System.out.print(array[i] + " "); 23 } 24 System.out.print("] "); 25 26 array = StraightInsertionSort.straightInsertionSort(array); 27 System.out.print("排好序的数组:[ "); 28 for (int i = 0; i < array.length; i++) { 29 System.out.print(array[i] + " "); 30 } 31 System.out.print("]"); 32 } 33 34 /** 35 * 选择排序 36 */ 37 public static void simpleSelectionSort() { 38 System.out.print("待排序数组:[ "); 39 for (int i = 0; i < array.length; i++) { 40 System.out.print(array[i] + " "); 41 } 42 System.out.print("] "); 43 44 array = SimpleSelectionSort.simpleSelectionSort(array); 45 System.out.print("排好序的数组:[ "); 46 for (int i = 0; i < array.length; i++) { 47 System.out.print(array[i] + " "); 48 } 49 System.out.print("]"); 50 51 } 52 53 public static void main(String[] args) { 54 // SortTest.straightInsertionSortTest(); 55 56 SortTest.simpleSelectionSort(); 57 58 } 59 }
原文:http://www.cnblogs.com/trfizeng/p/4307723.html