數據結構思維(二) 算法分析

1.簡單算法分類
  • 常數時間O(1):不依賴於輸入
  • 線性O(n):依賴於輸入,並跟輸入量大小成正比
  • 平方O(n^2 ):隨着n的增長變爲n^2
2.簡單排序
public class SelectionSort {

    /**
     * Swaps the elements at indexes i and j.
     */
    public static void swapElements(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    /**
     * Finds the index of the lowest value
     * starting from the index at start (inclusive)
     * and going to the end of the array.
     */
    public static int indexLowest(int[] array, int start) {
        int lowIndex = start;
        for (int i = start; i < array.length; i++) {
            if (array[i] < array[lowIndex]) {
                lowIndex = i;
            }
        }
        return lowIndex;
    }

    /**
     * Sorts the elements (in place) using selection sort.
     */
    public static void selectionSort(int[] array) {
        for (int i = 0; i < array.length; i++) {
            int j = indexLowest(array, i);
            swapElements(array, i, j);
        }
    }
}

swap()是常數級操作,時間恆定
indexLowest()複雜度,同n-start有關,屬於線性關係
selectionSort(),需要算n(n-1)/2,屬於平方關係


原書鏈接:https://wizardforcel.gitbooks.io/think-dast/content/1.html
GitHub鏈接(提供源碼):https://github.com/huoji555/Shadow/tree/master/DataStructure

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