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

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

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


猜你喜欢

转载自blog.csdn.net/manmandong123/article/details/80298979