數據序列1: 13-17-20-42-28 利用插入排序,13-17-20-28-42. Number of swap:1;
數據序列2: 13-17-20-42-14 利用插入排序,13-14-17-20-42. Number of swap:3;
若是數據序列基本有序,使用插入排序會更加高效。java
在要排序的一組數中,根據某一增量分爲若干子序列,並對子序列分別進行插入排序。
而後逐漸將增量減少,並重覆上述過程。直至增量爲1,此時數據序列基本有序,最後進行插入排序。shell
平均時間複雜度:spa
/** * 希爾(Shell)排序 * * @author Administrator * */ public class ShellSort { /* * 數據序列1: 13-17-20-42-28 利用插入排序,13-17-20-28-42. Number of swap:1; 數據序列2: * 13-17-20-42-14 利用插入排序,13-14-17-20-42. Number of swap:3; * 若是數據序列基本有序,使用插入排序會更加高效。 * * 基本思想: 在要排序的一組數中,根據某一增量分爲若干子序列,並對子序列分別進行插入排序。 * 而後逐漸將增量減少,並重覆上述過程。直至增量爲1,此時數據序列基本有序,最後進行插入排序。 */ public static void main(String[] args) { // TODO Auto-generated method stub int[] arr = new int[] { 2, 3, 2, 5, 6, 1, -2, 3, 14, 12, 3, 8, 55, 44, -10 }; shellSort(arr); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } private static void shellSort(int[] arr) { int incre = arr.length; while (incre > 0) { incre = incre / 2; for (int i = 0; i < incre; i++) { for (int j = i + incre; j < arr.length; j += incre) { for (int k = j; k > i; k -= incre) { if (arr[k] < arr[k - incre]) { int temp = arr[k]; arr[k] = arr[k - incre]; arr[k - incre] = temp; } else { break; } } } } } } }