Selection Sort
在Java中,接口类型可用来声明一个变量,它们可以成为一个空指针,或是被绑定在一个以此接口实现的对象。
“选择排序”是指:重复地在剩余的元素里选择最小值。
1.找到最小值。与第一个元素交换。
2.找到第2个最小值。与第2个元素交换。
3.找到第3个最小值。与第3个元素交换。
4.不断寻找最小值并且与合适位置的值进行交互,直到列表为有序的。
It is called selection sort because it repeatedly selects the smallest remaining item:
1.Find the smallest elemeent.Swap it with the first element.
2.Find the second smallest element.Swap it with the second element.
3.Find the third smallest element.Swap it with the third element.
4.Repeat finding the smallest and swapping in the correct position until the list is sorted.
Java语言实现选择排序:
Implementaion in java for selection sort:
package sort.sortImp;
public class SelectionSort {//非递减顺序
public static void selectionSort(Comparable[] array){
for (int i = 0; i < array.length; i++) {
int min = i;
for(int j=i+1; j<array.length; j++){
if(isLess(array[j] ,array[min])){
min = j;
}
}
swap(array,i,min);
}
}
//returns true if Comparable j is less than min
private static boolean isLess(Comparable j, Comparable min){
int comparison = j.compareTo(min); //+1 :j > min,-1 :j<min ,0: j=min
return comparison < 0;
}
private static void swap(Comparable[] array,int i, int j){
Comparable temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static <E> void printArray(E[] array){
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
//Check if array is sorted
public static boolean isSorted(Comparable[] array){
for(int i=1; i<array.length; i++){
if(isLess(array[i],array[i-1])){
return false;
}
}
return true;
}
public static void main(String[] args) {
Integer[] intArray = {34,17,23,35,45,9,1};
System.out.println("Unsorted Array:");
printArray(intArray);
System.out.println("\nIs intArray sorted?"+isSorted(intArray));
selectionSort(intArray);
System.out.println("\nSelection sort:");
printArray(intArray);
System.out.println("\nIs intArray sorted?"+isSorted(intArray));
String[] stringArray = {"z","g","c","o","a","@", "b", "A", "0", "."};
System.out.println("\n\nUnsorted Array:");
printArray(stringArray);
System.out.println("\n\nSelection sort:");
selectionSort(stringArray);
printArray(stringArray);
}
}