標籤:static -- wap return http 思想 ftp 自己 get
快速排序演算法的思想
快速排序演算法本質上通過把一個數組劃分成倆個子數組,然後遞迴的調用自己為每一個子數組進行快速排序來實現的,它應用了劃分演算法和遞迴思想,具體的劃分演算法參考http://www.cnblogs.com/iwebkit/p/7623350.html,只要把劃分演算法弄明白基本快速排序也就明白了。
快速排序演算法的步驟
1.把數組劃分成左右倆子數組。
2.調用自身對左數組進行排序。
3.調用自身對右數組進行排序。
快速排序演算法的樞紐選擇
在我之前寫的劃分演算法中,我們的樞紐是自己定義的,但是在快速排序中,我們需要將數組中的某一項作為樞紐,為了便於理解,我們將待劃分的右數組的最右端的資料項目作為樞紐,劃分完成後,將樞紐和右子數組的最左端的資料項目交換位置就行了
快速演算法的效率
O(N*logN)
快速排序的java程式
在程式中的注釋我唯寫了快速排序中的劃分演算法和單獨的劃分演算法的不同之處,如果想瞭解劃分排序請看http://www.cnblogs.com/iwebkit/p/7623350.html,程式中紅色的代碼是不同之處。
package sy;class ArrayIns{ private long[] theArray; private int nElems; public ArrayIns(int max){ theArray = new long[max]; nElems = 0; } public void insert(long value){ theArray[nElems] = value; nElems++; } public void display(){ System.out.print("A = "); for(int j = 0; j < nElems; j++) { System.out.print(theArray[j] + " "); } System.out.print(""); } //快速排序,因為我們不想在調用的時候還要書寫參數,所以將真正的快速排序放在該方法之中。 public void quickSort(){ recQuickSort(0,nElems - 1); } //真正的快速排序 public void recQuickSort(int left,int right) { //當需要劃分的數組只有一個資料項目時,快速排序結束 if(right - left < 1) { return; } else { //定義當前數組的最後一個資料項目為樞紐 long pivot = theArray[right]; //調用劃分演算法,返回樞紐的索引值然後賦值給pivotIndex int pivotIndex = partitionIt(left,right,pivot); //遞迴快速演算法,這個遞迴的是當前數組的左側小數組 recQuickSort(left,pivotIndex - 1); //遞迴快速演算法,這個遞迴的是當前數組的右側小數組 recQuickSort(pivotIndex + 1,right); } } //快速排序中的劃分演算法 public int partitionIt(int left,int right,long pivot) { //定義左指標,因為內層while的theArray[++leftPtr]先自增了,所以這裡先減一 int leftPtr = left - 1; //定義右指標 //這裡說明一下,在劃分演算法中,因為內層while的theArray[++leftPtr]先自減,這裡先加一為right + 1,但是在快速演算法中,我們將的最後一項也數組就是索引值為right的資料項目作為樞紐,所以我們取right - 1項,所以這裡我們不再加一了 int rightPtr = right; while(true) { while(leftPtr < right && theArray[++ leftPtr] < pivot) { } while(rightPtr > left && theArray[-- rightPtr] > pivot) { } //如果左右指標相遇則劃分演算法結束 if(leftPtr >= rightPtr) { break; } else { swap(leftPtr,rightPtr); } } //之前將數組的最後一項也就是索引值為right的資料項目作為樞紐,這裡我們將樞紐放在他應該在的位置也就是倆個小數組中間的位置,也就是左指標的位置 swap(right,leftPtr); return leftPtr; } //交換方法 public void swap(int index1,int index2) { long temp = theArray[index1]; theArray[index1] = theArray[index2]; theArray[index2] = temp; }}class App{ public static void main(String[] args) { int maxSize = 16; ArrayIns arr; arr = new ArrayIns(maxSize); for(int j = 0; j < maxSize; j++) { long n = (int)(java.lang.Math.random()*199); arr.insert(n); } arr.display(); arr.quickSort(); arr.display(); }}
快速排序演算法