选择排序 java实现
public class SortArray {
?
public static <T extends Comparable<? super T>> 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);
? ? ? ? ?}
}
? ?//在数组中找出最小值的索引
private static <T extends Comparable<? super T>> 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;
}
}
return indexOfMin;
}
//交换数组元素位置
private static void swap(Object[] a,int i ,int j){
Object temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
Integer a[] = {9,8,7,6,5,4,3,2,1};
Integer n ?= a.length;
SortArray.selectionSort(a, n);
for(Integer i: a){
System.out.print(i+" ");
}
}
}
//递归实现选择排序public class TestSort {? ?public static <T extends Comparable<? super T>> void sort(T[] a,int first,int last){ ? //递归不能正常停止,设置正确停止判断 ? if(first < last){ ? int indexOfSmallest = getIndexOfSmallest(a, first, last); ? swap(a, first, indexOfSmallest); ?? ? sort(a, first + 1, last); ? } ??? ?}? ?? ?//在数组中找出最小值的索引private static <T extends Comparable<? super T>> int getIndexOfSmallest(T[] a,int first,int last){T min = a[first];int indexOfMin = first;for(int index = first;index <= last;index++){if(a[index].compareTo(min) < 0){min = a[index];indexOfMin = index;}}return indexOfMin;}//交换数组元素位置private static void swap(Object[] a,int i ,int j){Object temp = a[i];a[i] = a[j];a[j] = temp;}public static void main(String[] args) {Integer a[] = {9,8,6,4,39,94,988,34,234,34324,34225};TestSort.sort(a, 0, a.length-1);for(Integer m :a){System.out.print(m+" ");}}}
经测试是正确的~~~