標籤:java 希爾排序
效率:O(n*logN)
package sort;import utils.Util;/** * 希爾排序 * 以h為間隔,進行比較。 按一定公式,先求出最大的間隔h * 當h值大時,需要移動的元素個數就少,但移動的距離長。 內部以h步長的元素做插入排序 * 當h減小時,每趟排序需要移動的元素個數增多,但此時已接近於它們排序後的最終位置,這對於插入排序更有效率 * * @author stone * @date 2015-7-22 下午4:39:41 */public class ShellSort {public static void main(String[] args) {//int[] ary = Util.generateIntArray(10);int[] ary = {7, 1, 3, 6, 4, 5, 2, 0};Util.printArray(ary);sort(ary);Util.printArray(ary);}static void sort(int[] ary) {int h = 1;while (ary.length/3 > h) {h = 3 * h + 1;}while (h > 0) {int j, temp;for (int i = h; i < ary.length; i++) {temp = ary[i];//j = i;//while (j > h - 1 && ary[j - h] >= temp) {//ary[j] = ary[j - h];//j -= h;//}for (j = i; j > h - 1 && ary[j - h] >= temp; j -= h) {ary[j] = ary[j - h];}ary[j] = temp;//System.out.println("移動---------");//Util.printArray(ary);}h = (h - 1) / 3;}}/* * [7, 1, 3, 6, 4, 5, 2, 0] * h=4 * temp = ary[4], i = 4 * 1: [0] 比 [4] [0]>[4] [4]=[0] [0] = temp * 2: temp=ary[5] [1] 比 [5] 不變 * 3: temp=ary[6] [2] 比 [6] 變化 [6]=[2] [2]=temp * 4: temp=ary[7] [3] 比 [7] 變化 [7]=[3] [3]=temp * 現在: * [4, 1, 2, 0, 7, 5, 3, 6] * * [1, 4, 2, 0, 7, 5, 3, 6] 1 移位次數 * [1, 2, 4, 0, 7, 5, 3, 6] 1 * [0, 1, 2, 4, 7, 5, 3, 6] 3 * [0, 1, 2, 4, 7, 5, 3, 6] * [0, 1, 2, 4, 5, 7, 3, 6] 1 * [0, 1, 2, 3, 4, 5, 7, 6] 3 * [0, 1, 2, 3, 4, 5, 6, 7] 1 * * 以h為間隔, 按一定公式,先求出最大的間隔h * while(h>0) { * for(i=h;i<len;i++) { * for(迴圈比較[h]和[i-h]的值,並移位) * } * h = 。。。 最後一輪時 h=1. 這時 i=n i比(i-1),(i-1)再比((i-1)-1) 從後向前相鄰兩個相比 * } */}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Java 希爾排序