希尔排序比插入排序快很多,原因是,当
h
值大的时时候,数据项每一趟排序需要移动的元素的个数很少,但是数据项移动的距离很长。这是非常有效率的。当
h
减小时,每一趟排序需要移动的元素的个数增多。但是此时数据项已经接近于它们排序后最终的位置,这对于插入排序可以更有效率。正是这两种情况的结合才使希尔排序效率这么高。希尔排序的代码:
class shellShort { privatestaticlong[] theArray; privatestaticint nElems; publicstaticvoid display() { System.out.print("A="); for (int j=0; j<nElems; j++) { System.out.print(theArray[j] +""); } System.out.println(""); } publicstaticvoid shellSort() { int inner,outer; long temp; int h =1; while (h <= nElems/3) //find initial value of h { h = h*3+1; } while (h>0) //decreasing h, util h=1 { //h-sort the file for (outer=h; outer<nElems; outer+=h) { temp = theArray[outer]; inner = outer; // one subpass(eg 0,4,8) while (inner > h-1&& theArray[inner-h] >= temp) { theArray[inner] = theArray[inner-h]; inner -= h; } theArray[inner] = temp; }//end for h = (h-1)/3; //decrease h }//end while }//end shellSort() publicstaticvoid main(String[] args) { //System.out.println("Hello World!"); theArray =newlong[1000]; for (int j=0; j<1000; j++) { long n = (int)(java.lang.Math.random()*99); theArray[j] = n; nElems++; } //shellShort.display(); System.out.println(new java.util.Date()); shellShort.shellSort(); System.out.println(new java.util.Date()); //shellShort.display(); } }
class QuickSort2 { privatestaticlong[] theArray; privatestaticint nElems; publicstaticvoid display() { System.out.print("A="); for (int j=0; j<nElems; j++) { System.out.print(theArray[j] +""); } System.out.println(""); } publicstaticvoid quickSort() { recQuickSort(0, nElems -1); } publicstaticvoid recQuickSort(int left, int right) { int size = right-left+1; if (size <=3) //manual sort if small { manualSort(left, right); } else//quick sort if large { long median = medianOf3(left, right); //median item //partition range int partition = partitionIt(left, right, median); recQuickSort(left, partition-1);//sort left side recQuickSort(partition+1, right);//sort right side } }//end recQuickSort() publicstaticlong medianOf3(int left, int right) { int center = (left+right)/2; //order left & center if(theArray[left] > theArray[center]) swap(left,center); //order left & right if(theArray[left] > theArray[right]) swap(left, right); //order right & center if(theArray[center] > theArray[right]) swap(center, right); swap(center, right-1); //put pivot on right return theArray[right-1]; }//end medianOf3() publicstaticint partitionIt(int left, int right, long pivot) { int leftPtr = left; //right of first elem int rightPtr = right-1; //left of pivot while (true) { //find bigger item while (theArray[++leftPtr] < pivot) { ; }