經典排序演算法 - 插入排序Insert Sort
阿新 • • 發佈:2018-11-06
最近學習了一下排序演算法,寫篇文章記錄一下,詳細講解網上有很多,可以自己去查
插入排序Insert Sort
直接插入排序就是依次將無序表中的資料插入到有序表的適當位置,使有序表仍有序,直到全部插入為止。插入排序的時間複雜度是O(n²),是穩定排序。
[ 2 ] 4 5 1 3 ↑ │ └─────┘ [ 2 4 ] 5 1 3 ↑ │ └─────┘ [ 2 4 5 ] 1 3 ↑ │ └─────────────────┘ [ 1 2 4 5 ] 3 ↑ │ └─────────────┘ [ 1 2 3 4 5 ]
演算法描述(Java):
import java.util.Arrays; public class SortAlgorithm { public static void insertSort(int[] array) { int temp = 0; for (int i = 1; i < array.length; ++i) { temp = array[i]; int j = i - 1; while (j >= 0 && temp < array[j] ) { array[j + 1] = array[j]; j--; } array[j + 1] = temp; } } public static void main(String[] args) { int[] array = {2,4,5,1,3}; insertSort(array); System.out.println(Arrays.toString(array)); } }