0081 插入排序簡單分析

package sort;

public class InsertSorting {
    public static void insertSort(int[] nums){
        if (null == nums || nums.length < 2)
            return;
        for (int i = 0; i < nums.length; i++)
            for (int j = i; j>0; j--){
               if(nums[j] < nums[j - 1]){
                    int tmp = nums[j];
                    nums[j] = nums[j - 1];
                    nums[j - 1] = tmp;
            }
        }
    }
    //最好情況:數組已經有序,只有比較,T(n)= 1 + 2 +...+ n-1 =O(n^2)
    //最壞情況:數組逆序,做全部比較和交換,T(n)=2*(1+2+...+n-1)=O(n^2)
    //平均時間複雜度:O(n^2),空間複雜度O(1)


    public static void main(String[] args){
        int[] nums = {2,0,1,9,1,0,2,8,1,23};
        insertSort(nums);
        for (int num: nums)
            System.out.print(num+" ");
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章