Selection sort的java语言实现

选择排序(Selection Sort)的实现

思想如下:

  • First,find the smallest element in the array,and exchange it with the element in the first position
  • Then ,find the second smallest element in the array.and exchange it with the element in the second position
  • continue in this way until the entire array is sorted

java 实现代码如下:

public class SelectionSort {

    public static void main(String[] args) {
        //选择排序的实现
        int[] a={9,8,7,6,5,4,3,2,1,0};
        System.out.println("排序前的数组如下:"+Arrays.toString(a));
        int min;
        for(int i=0;i<a.length-1;i++){
            min=i;
            int j=i+1;
            for(;j<a.length;j++){//在数组中没有排序的部分中寻找的最小值
                if(a[min]>a[j]){
                    min=j;

                }

            }
            //每次循坏找到最小值后就与当前位置进行交换
            swap(a,i,min);

        }
        System.out.println("排序后的数组如下:"+Arrays.toString(a));


    }
    public static void swap(int [] a,int i,int j){
        int temp;
        if(i!=j){
            temp=a[i];
            a[i]=a[j];
            a[j]=temp;

        }

    }

}

总结

  • 选择排序至多会交换n次
  • 选择排序的时间复杂度为O(n^2);

So, Selection sort can be useful when memory write is a costly operation.

关于选择排序的C语言实现,可以查看这里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值