1,采用选择排序对元素进行排列时,元素之间需要进行比较,因此需要实现Comparable接口。即,>. 更进一步,如果允许待比较的类型可以和它的父类型进行比较,则需要写成:, 其中 super T> 表示 T 的任意超类。
2,SelectionSortArray.java 实现了选择排序的迭代形式和递归形式。具体代码如下:
public class SelectionSortArray {
? ? /*
? ? * Task:将数组中前n个对象按升序排列
? ? * @param a Comparable 对象的数组
? ? * @param n 大于0的整数,表示数组的长度
? ? */
? ? public static > void selectionSort(T[] a, int n){
? ? ? ? for(int index = 0; index < n-1; index++){
? ? ? ? ? ? int indexOfNextSmallest = getIndexOfSmallest(a, index, n-1);
? ? ? ? ? ? swap(a, index, indexOfNextSmallest);
? ? ? ? }
? ? }
? ?
? ? //返回索引first 至 索引last 之间的最小值的索引
? ? private static > int getIndexOfSmallest(T[] a, int first, int last){
? ? ? ? T min = a[first];
? ? ? ? int indexOfMin = first;
? ? ? ? for(int index = first + 1; index <= last; index++){
? ? ? ? ? ? if(a[index].compareTo(min) < 0){
? ? ? ? ? ? ? ? min = a[index];
? ? ? ? ? ? ? ? indexOfMin = index;
? ? ? ? ? ? }//end if
? ? ? ? }
? ? ? ? return indexOfMin;
? ? }
? ?
? ? //交换数组元素不涉及compareTo方法,因而使用Object作为元素类型
? ? private static void swap(Object[] a, int i, int j){
? ? ? ? Object temp = a[i];//交换的并不是引用,而是具体的元素的值
? ? ? ? a[i] = a[j];
? ? ? ? a[j] = temp;
? ? }
? ?
? ? //选择排序的递归方法
? ? public static > void selectionSort_Recursive(T[] a, int n){
? ? ? ? selectionSort(a, 0, n - 1);
? ? }
? ?
? ? private static > void selectionSort(T[] a, int first, int last){
? ? ? ? if(first < last)
? ? ? ? {
? ? ? ? ? ? int indexOfNextSmallest = getIndexOfSmallest(a, first, last);
? ? ? ? ? ? swap(a, first, indexOfNextSmallest);
? ? ? ? ? ? selectionSort(a, first + 1, last);
? ? ? ? }
? ? }
}