標籤:資料結構 排序演算法 希爾排序 插入排序
上篇總結中主要實踐了演算法的內排序的選擇排序,那麼接下來我們繼續實踐插入排序排序的兩種:直接插入排序和希爾排序演算法。
-----直接插入排序
package com.sort;/** * 直接插入排序 * * @author weixing-yang * * 演算法思路: * 每步將一個待排序的元素,插入到前面已排序好的一組元素中的適當位置, * 直到所有元素全部出入完成為止。 */public class InsertionSort {public void insertionSort(int[] arr, int n) {for (int i = 1; i < n - 1; i++) {int temp = arr[i];//取得第二個元素if (temp < arr[i - 1]) {int j;for (j = i-1; j >= 0 && arr[j] > temp; j--) {arr[j+1] = arr[j];}arr[j+1] = temp;}}}}----- 希爾排序
希爾排序(Shell Sort)是插入排序的一種,是將整個無序列分割成若干小的子序列分別進行插入排序。
package com.sort;/** * 希爾排序 * @author weixing-yang * *演算法思路 *先取出一個正整數d1<n,把所有序號相隔d1的元素分別放置一個組中,各組內進行直接插入排序。 * 然後在取d2<d1,重複上述分組和排序操作。直至di =1,即所有記錄放到一組中排序為止。 * */public class ShellSort {public void shellSort(int[] arr, int n){int i,j,k,temp;k = (n-1)/2;while(k > 0){for (i = k; i < n-1; i++) {temp = arr[i];for (j = i-k; j >= 0 && arr[j] > temp; j -= k) {arr[j+k] = arr[j];}arr[j+k] = temp;}k/=2;}}}-----測試函數
package com.sort;public class Main {public static void main(String[] args){int[] array = {36, 25, 45,40, 12, 34, 55}; int n = array.length;InsertionSort insert = new InsertionSort();ShellSort shell = new ShellSort();long start = System.currentTimeMillis();//insert.insertionSort(array, n);shell.shellSort(array, n);long end = System.currentTimeMillis();long sum = end - start;System.out.println("排序花費的總毫秒數:"+sum);for (int i = 0; i < array.length; i++) {System.out.print(array[i]+" ");}}}
-----運行結果
排序花費的總毫秒數:012 25 34 36 40 45 55
直接插入排序是穩定排序,時間複雜度是n2,希爾排序是不穩定排序。
@@------->>下篇繼續實踐歸併排序的兩種排序演算法。