概念java
從第2個元素開始,將每個元素插入到已經排好序的序列中,獲得一個新的排好序的序列oop
Java版實現blog
public static void insert(Integer[] array) { Integer s; int j; for (int i = 1; i < array.length; i++) { if (array[i] < array[i-1]) { s = array[i]; for (j = i-1; j >= 0 && array[j] > s; j--) array[j+1] = array[j]; // move the element backward array[j+1] = s; // put the ith element in the right place } // end if the element i-1 larger than element i } // end for loop and compare length-1 times }
時間複雜度分析排序
最差狀況,初始爲倒序序列,須要比較的次數爲(n-1)(n+2)/2次,須要移動(n+4)(n-1)/2次,時間複雜度爲O(n2)element
最好狀況,初始爲已排序序列,須要比較的次數爲n-1次,須要移動0次,時間複雜度爲O(n)it
與冒泡和簡單選擇排序比較,我的以爲並無體現優點class
空間複雜度分析im
須要的輔助空間爲O(1)static