標籤:複雜度 冒泡 否則 快速排序 分解 .so splay ret nbsp
快速排序是冒泡排序的最佳化,是一種非常高效的排序, 甚至是目前為止最高效的排序,其思想是這樣的:設數組a中存放了n個資料元素,low為數組的低端下標,high為數組的高端下標,從數組a中任取一個元素(通常取a[low])做為標準元素,以該標準元素調整數組a中其他各個元素的位置,使排在標準元素前面的元素均小於標準元素,排在標準元素後面的均大於或等於標準元素,由此將數組根據標準元素分解成了兩個子數組。對這兩個子數組中的元素分別再進行方法類同的遞迴快速排序。演算法的遞迴出口條件是low≥high。
可能講到這裡你不太懂, 但是看完步驟之後你一定會懂得。
步驟如下:
1、有一個資料a [ n ],
2、定義一個低端下標 low 和 一個高端下標 high;
3、定義i, j 兩個變數;
4、設定條件:如果 low >= high 演算法結束,否則進行以下步驟;
5、取數組第一個數作為標準 int standar, j = high, i = low
6、當 i < j 時, 從數組最後向前尋找,如果條件滿足 i < j(因為可能在找的過程中i 和 j 的值發生了改變) , 並且a[ j ] >= standar, j--
不滿足時停止 ,令 a[ i ] = a[ j ], 然後 i 的下標右移 i++;
7、當 i < j 時, 從數組開始向後尋找,如果條件滿足 i < j(因為可能在找的過程中i 和 j 的值發生了改變) , 並且a[ i ] <= standar, i++
不滿足時停止 ,令 a[ j ] = a[ i ], 然後 i 的下標左移 j--;
8、退出整個迴圈體、令 i 位置的值為standar
9、遞迴數組的兩個子數組
對應代碼為:
package quickSort;public class QuickSort { public int[] quicksort(int a[], int low, int high) { int i, j; if (low >= high) { return a; } else { int standar = a[low]; i = low; j = high; while (i < j) { while (i < j && a[j] >= standar) { j--; } if(i < j){ a[i] = a[j]; i++; } while (i < j && a[i] < standar) { i++; } if(i < j){ a[j] = a[i]; j--; } } a[i] = standar; quicksort(a, low, i - 1); quicksort(a, i + 1, high); return a; } } public int[] sort(int a[], int low, int high) { a = quicksort(a, low, high); return a; }}
測試類別為:
package Test;import org.omg.CORBA.Current;import bubbleSort.BubbleSort;import insertSort.InsertSort;import quickSort.QuickSort;import selectSort.SelectSort;public class Test { public static void main(String[] args) { QuickSort quickSort = new QuickSort(); int[] array = createArray(); long ct1 = System.currentTimeMillis(); int[] arrays = quickSort.sort(array, 0, array.length - 1); long ct2 = System.currentTimeMillis(); display(arrays); System.out.println("所消耗的時間:" + (ct2 - ct1)); } public static void display(int[] arrays) { System.out.println("排序後資料:"); for (int i = 0; i < arrays.length; i++) { System.out.print(arrays[i] + "\t"); if ((i + 1) % 10 == 0) { System.out.println(); } } System.out.println(); } public static int[] createArray() { int[] array = new int[100000]; System.out.println("數組中元素是:"); for (int i = 0; i < 100000; i++) { array[i] = (int) (Math.random() * 1000); System.out.print(array[i] + "\t"); if ((i + 1) % 10 == 0) { System.out.println(); } } System.out.println(); return array; }}
時間複雜度:
經過計算:10000個數的排序時間為2 ms, 100000個數的排序時間為 40ms , 比上次測試的 冒泡排序14000ms 快了 300多倍。
快速排序(java)