1. 程式人生 > >Insertion Sort

Insertion Sort

emp strong arr img pub static ret bsp 掃描

https://www.youtube.com/watch?v=kU9M51eKSX8

技術分享圖片

技術分享圖片

插入排序

插入排序(Insertion Sort)的基本操作就是將一個數據插入到已經排好序的有序數據中,從而得到一個新的、個數加一的有序數據,算法適用於少量數據的排序,時間復雜度為O(n^2)。是穩定的排序方法。

插入排序的基本思想是:每步將一個待排序的紀錄,按其關鍵碼值的大小插入前面已經排序的文件中適當位置上,直到全部插入完為止。

算法描述

具體算法描述如下:

  1. 從第一個元素開始,該元素可以認為已經被排序
  2. 取出下一個元素,在已經排序的元素序列中從後向前掃描
  3. 如果該元素(已排序)大於新元素,將該元素移到下一位置
  4. 重復步驟3,直到找到已排序的元素小於或者等於新元素的位置
  5. 將新元素插入到下一位置中
  6. 重復步驟2~5

主意,這個和 selection sort 很像,insertion sort 是從後往前, selection sort 是從前往後。

 1 public class InsertionSort {
 2     public int[] sort(int[] arr){
 3         if (arr == null) return arr ;
 4         //默認第一位(5)已經SORT 好,從第二位(1)開始 倒著往回比較: 如果比 5 小 則把 5 換過來
 5
// 5 1 3 6 4 6 for (int i = 1; i < arr.length; i++) { 7 //倒序 J>0 因為下面 有 arr[j-1] 千萬小心 8 for (int j = i; j >0; j--) { 9 //swap 5 1 to 1 5 10 if (arr[j]<arr[j-1]){ 11 int temp = arr[j-1]; 12 arr[j-1] = arr[j];
13 arr[j] = temp ; 14 } 15 } 16 } 17 return arr ; 18 } 19 20 public static void main(String[] args) { 21 InsertionSort insertionSort = new InsertionSort() ; 22 int[] arr = new int[]{5,1,3,6,4} ; 23 int[] res = insertionSort.sort(arr) ; 24 Arrays.stream(res).forEach(a-> System.out.println(a)); 25 } 26 }

技術分享圖片

Insertion Sort