数据结构那些事(个人理解向)

2018年5月13日14点00分 点击跳转

一、选择排序
package adward.algo;

public class SelectionSort {

    private SelectionSort(){}

    public static void sort(Comparable[] arr){

        int n = arr.length;
        for( int i = 0 ; i < n ; i ++ ){
            // 寻找[i, n)区间里的最小值的索引
            int minIndex = i;
            for( int j = i + 1 ; j < n ; j ++ )
                if( arr[j].compareTo(arr[minIndex]) < 0)
                    minIndex = j;
            swap( arr , i , minIndex);
        }
    }

    private static void swap(Object[] arr, int i, int minIndex) {
        Object temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }

    public static void main(String[] args) {

        Integer[] arr = {10,9,8,7,6,5,4,3,2,1};   //此处Integer可换为其他类型
        SelectionSort.sort(arr);
        for( int i = 0 ; i < arr.length ; i ++ ){
            System.out.print(arr[i]);
            System.out.print(' ');
        }
        System.out.println();
    }
}

注:应用Java的comparable接口和泛型对数组排序。对选择排序的理解可为:从第一个位置开始,对以后的所有位置上的值进行对比后调整顺序(往右走

二、插入排序
package adward.algo;

public class InsertionSort {

    private InsertionSort(){}

    public static void sort(Comparable[] array){
        int length = array.length;
        for (int i=0; i < length; i++){
            for (int j = i; j > 0 && array[j].compareTo(array[j-1]) < 0; j--){
                swap(array, j, j-1);
            }
        }
    }
    private static void swap(Object[] arr, int i, int j){
            Object temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
    }

    public static void main(String[] args){
        Integer[] array = {10,9,8,7,6,5,4,3,2,1};
        InsertionSort.sort(array);
        for (int i = 0; i < array.length; i++){
            System.out.print(array[i] + " ");
        }
        System.out.println();
    }
}

注:同一。对插入排序的理解可为:从第一个位置开始,对之前的所有位置上的值进行对比后调整顺序(往左走


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值