SelectionSort选择排序

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);

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值