快速排序
描述:通過若干次劃分的方法完成待排序序列的排序。劃分是通過一次遍歷用基準數將待排序序列分成兩個部分,在基準數左邊的部分都小於等於該基準數,在基準數右邊的都大於等於該基準數。經過一次劃分後,待排序序列劃分成兩個獨立的序列,然後分別將劃分過後的兩個獨立序列當做待排序序列再進行劃分。
Java代碼:
// 劃分方法返回基準位置,
// 基準位置左邊的所有值都小於等於基準位置的值,
// 基準位置右邊的所有值都大於等於基準位置的值
public static int partition(int[] array,int low,int high) {
// 一般去第一個數爲基準,如果使算法不受待排序序列影響,可以隨機選取一個位置,將給位置與第一個位置交換。
// 此時,low指向的位置可以被覆蓋
int tmp= array[low];
// 循環終止條件,當low和high相等時,表示當前只剩下一個元素,不需要比較
while (low< high) {
// 從右邊向左邊依次尋找第一個不滿足大於基準數的位置
while (low< high && array[high] > tmp)
high--;
// 如果low位置小於high,將找到的第一個不滿足大於基準數的位置high指向數組覆蓋low指向的位置
// 此時,high指向的位置可以被覆蓋
if (low< high)
array[low++] = array[high];
// 從左邊向右邊依次尋找第一個不滿足小於等於基準數的位置
// 判斷條件變爲小於等於是因爲待排序序列可能存在多個相等的值,
// 等於用於過濾多個相等的值,該等於也可以用在從右向左比較中,
// 但是從左到右和從右到左只能夠有一個帶等於號。
while (low< high && array[low] <= tmp)
low++;
// 如果low位置小於high,將找到的第一個不滿足大於基準數的位置high指向數組覆蓋low指向的位置
// 此時,low指向的位置可以被覆蓋
if (low< high)
array[high--] = array[low];
}
// 每次循環入口是low位置可以被覆蓋,第一次從右到左查找後high位置可以被覆蓋,
// 第二次從左到右查找後low位置可以被覆蓋,然後又到循環入口
// 循環中待比較序列位置爲[low+1,high]
// 循環結束的low位置爲最終基準的位置
array[low] = tmp;
// 返回最終的基準位置
return low;
}
// 通過劃分方法,將待排序序列[sta,end]劃分爲兩個待排序序列[sta,part-1]和[part+1,end]
public static void quickSort(int[] array,int sta,int end) {
if (sta>= 0 && sta < end) {
int part= partition(array, sta, end);
quickSort(array, sta, part - 1);
quickSort(array, part + 1,end);
}
}
測試代碼:
public static boolean checkSort(int[] array) {
for (int i =1; i < array.length; i++) {
if(array[i] < array[i - 1])
return false;
}
return true;
}
public static void printArray(int[] array) {
for (int i =0; i < array.length; i++)
System.out.print(i+ ":" + array[i] + " ");
System.out.println();
}
public static void testQuickSort(int count,int size) {
Random random = new Random();
int[] array;
int length;
int errorCount = 0;
System.out.println("Start...");
while(count-- > 0) {
length = random.nextInt(size);
array = new int[length];
for (int i =0; i < length; i++)
array[i] = random.nextInt();
quickSort(array, 0, length -1);
if (!checkSort(array)){
errorCount++;
printArray(array);
}
}
System.out.println("End.The error QuickSort count is " + errorCount +" .");
}
測試報告:
運行程序testQuickSort(1000,100),即測試quickSort1000次,測試的數組長度在100以內的隨機數組成的待排序序列。測試成功。
問題拓展:
快速排序中的劃分方法partition可以用於:快速找出未知數組中第k大的數;快速找出未知數組中k個最大的數。
下載地址:
http://download.csdn.net/detail/ssuchange/6705807