1. 程式人生 > >算法系列之<快速排序>

算法系列之<快速排序>

quicksort n) param arr [] array code quick 成長

快速排序:

 /**
     * 快速排序
     * 最好情況下:每趟把原序列分成兩個長度幾乎相等的子序列
     * 最差情況下:每趟把原序列分成長度相差很大的兩個子序列
     * 平均時間復雜度:O(NLogN),空間復雜度O(logN)
     * case1:{1}
     * case2:{1,2}
     * case3:{1,2,3,4,5}
     * case4:{5,4,3,2,1}
     * case5:{8,9,10,2,3}
     * @param array1
     * @param low
     * @param high
     * 
@return */ public static void quickSort(int[] array1,int n,int low,int high){ if(low<high&&low>=0&&low<n&&high>=0&&high<n) { int vot = array1[low]; int i = low; int j = high; while(i<j) {
while (j > i && array1[j] > vot) { j--; } if (j > i) { if (array1[j] < vot) { int temp = array1[j]; array1[i] = temp; i++; } }
while (i < j && array1[i] <= vot) { i++; } if (i < j) { if (array1[i] > vot) { int temp = array1[i]; array1[j] = temp; j--; } } } if(i==j){ array1[i]=vot; } quickSort(array1, array1.length,low, j - 1); quickSort(array1, array1.length,i + 1, high); } }

算法系列之<快速排序>