SelectionsSort選択ソート

15268 ワード

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
        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("
Is intArray sorted?"
+isSorted(intArray)); selectionSort(intArray); System.out.println("
Selection sort:"
); printArray(intArray); System.out.println("
Is intArray sorted?"
+isSorted(intArray)); String[] stringArray = {"z","g","c","o","a","@", "b", "A", "0", "."}; System.out.println("

Unsorted Array:"
); printArray(stringArray); System.out.println("

Selection sort:"
); selectionSort(stringArray); printArray(stringArray); } }