直接插入排序
写法1:查找插入位置 后移腾出位置 插入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
public static void directSortInsertByFind(int[] data) { if (data == null) return; for (int i = 1; i < data.length; i++) { int toInsert = data[i], insertIndex; for (insertIndex = 0; insertIndex <= i - 1; insertIndex++) { if (data[insertIndex] > toInsert) break; } for (int k = i; k > insertIndex; k--) data[k] = data[k - 1]; data[insertIndex] = toInsert; } }
|
写法2:插入末尾 向前冒泡
插入已排序序列的默认,然后使用冒泡法,来调整插入元素的位置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
public static void directSortInsertByMaoPao(int[] data) { if (data == null) return; for (int i = 1; i < data.length; i++) { for (int j = i; j > 0; j--) { if (data[j] < data[j - 1]) { int t = data[j]; data[j] = data[j - 1]; data[j - 1] = t; } else { break; } } } }
|
改进写法:二分查找来找插入位置
使用二分查找来查找待插入元素的位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
public static void directSortInsertByHalfSearch(int[] data) { if (data == null) return; for (int i = 1; i < data.length; i++) { int key = data[i]; int j = FindInsertIndexByHalfSearch(data, i - 1, key); for (int k = i; k > j; k--) data[k] = data[k - 1]; data[j] = key; } }
private static int FindInsertIndexByHalfSearch(int[] data, int n, int key) { int left = 0, right = n; while (left <= right) { int mid = (left + right) / 2; if (data[mid] == key) { return mid; } if (data[mid] > key) right = mid - 1; else left = mid + 1; } right++; return right; }
|