/** * 算法策略:先用第一个数值做比较,与其后的每一个数比较,遇到比自己小的就记录下位置,然后用这个小的再去和后面的数比较。全部比较完毕, * 将当前最小的值与第一个位置的数值做交换。接下来用第二个数值比较(第一个数,你已经比较过,已经是最小的了),重复上面的步骤。直到比较完倒数第二个数为止。 * * * @author yaoyuan * */ public class SelectSort { @SuppressWarnings({ "rawtypes", "unchecked" }) public static void selectSort(Comparable[] data) { int intLength = data.length; for (int i = 0; i < intLength - 1; i++) { int minIndex = i; for (int j = i + 1; j < intLength; j++) { Comparable a = data[j]; Comparable b = data[minIndex]; if (b.compareTo(a) > 0) { minIndex = j; } } if (minIndex != i) { Comparable temp = data[i]; data[i] = data[minIndex]; data[minIndex] = temp; } } } public static void selectSort2(int[] data) { int dataLength = data.length; for (int i = 0; i < dataLength - 1; i++) { int minIndex = i; for (int j = i + 1; j < dataLength; j++) { if (data[minIndex] > data[j]) { minIndex = j; } } if (minIndex != i) { int temp = data[i]; data[i] = data[minIndex]; data[minIndex] = temp; } } } @SuppressWarnings("rawtypes") public static void main(String[] args) { Comparable[] c = { 45, 9, 23, 1, 4, 27, 5, 2 }; selectSort(c); for (int i = 0; i < c.length; i++) { System.out.println(c[i]); } int[] c1 = { 45, 9, 23, 1, 4, 27, 5, 2 }; selectSort2(c1); for (int i = 0; i < c1.length; i++) { System.out.println(c1[i]); } } }