高級排序--希爾排序

希爾排序

 

實際上是基於插入排序的,在插入排序中相比較的是相鄰的兩個元素,但是如果一個很小的數在數組的最右端,而他本應該是在最左端的,這樣的話所有中間的元素都要向右移動一位,並且執行了N次。希爾排序就是首先對大跨度的元素做比較並且進行移動,這樣的久相對有序了,再在這個基礎上進行普通的插入排序,效率就會高很多。

 

效率

 

快速排序>希爾排序>簡單排序

希爾排序在最壞的執行效率上和平均的執行效率上沒有差很多。

 

<!--StartFragment --> 

 

public class ShellSort {
	
	public static void main(String[] args) {
		int[] arr = {4,5,9,3,2,1,6,18,11,15,10};
		
		ShellSort.display(arr);
		ShellSort.shellSort(arr);
		System.out.println("------------------------------");
		ShellSort.display(arr);
	}
	
	public static void display(int[] theArray){
		int nElems = theArray.length;
		System.out.println("A=");
		for(int j = 0; j < nElems; j++){
			System.out.println(theArray[j] + " ");
		}
		System.out.println(" ");
	}
	
	public static void shellSort(int[] theArray){
		int inner,outer;
		
		//臨時變量
		int temp;
		
		//數組長度
		int nElems = theArray.length;
		
		//定義元素跨度數量
        int h=1;       

        //定義元素跨度基數   
        int n = 3;
        
        /**
         * 設置排序元素之間的位置 公式:h = h * n +1
         * 例:n=3 則元素跨度爲(0,4),(1,5),(2,6)...
         *   n=4 -->(0,5),(1,6),(2,7)...
         */
        while(h<=nElems/n){
        	  h=h*n+1;    //1,4,13,40,121,...   
        }
         
        while (h>0){
        	
        	/**
        	 * 這裏的for循環會執行2次
        	 * 第一次:  h=4 以元素跨度個數爲4的情況下循環一次(0,4),(1,5),(2,6)
        	 * 第二次:  h=1 也就執行插入排序對相鄰的元素進行比較
        	 */
	        for(outer=h;outer<nElems;outer++){
	        		
	        		/**
	        		 * 存儲基數 outer = h 位置的元素,每次outer++,比較的元素
	        		 * 位置也就向後移動一位0,4),(1,5)
	        		 * 移動的次數  數組長度 - h;
	        		 */
	                temp=theArray[outer];   
	                inner=outer;   
	               
	              /**
	               * 如果已經替換條件成則立進行替換
	               */
	              while(inner>h-1&&theArray[inner-h]>=temp){   
	                theArray[inner]=theArray[inner-h];
	                
	                //已經替換後,變更inner值,爲首元素(0,4)中的0,(1,5)中的1
	                inner-=h;   
	                }
	            //將換後的臨時值替換位置
	            theArray[inner]=temp;   
	        }
	        
	        //關鍵:這裏將元素基數變爲1,也就將這個運算變爲了插入排序。
            h=(h-1)/n;   
         }   
     }   
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章