本博客不再更新,更多精彩內容請訪問我的獨立博客
快速排序是很重要的排序算法,但是我在學的時候發現網上沒有特別好的例子所以自己動手寫了一個。
自己動手豐衣足食。
package sort;
import java.util.Random;
public class QuickSort {
@SuppressWarnings("unused")
public boolean initTestArray(int[] testArray) {// 初始化testArray
if (testArray == null)
return false;
Random random = new Random();
for (int i = 0; i < testArray.length; i++) {
testArray[i] = random.nextInt(200);
}
return true;
}
public boolean printTestArray(int[] testArray) {// 打印testArray中的內容
if (testArray == null)
return false;
for (int i = 0; i < testArray.length; i++) {
System.out.print(testArray[i] + ",");
}
System.out.println();
return true;
}
public static boolean quickSort(int[] testArray, int left, int right) {
if(testArray==null)
return false;
if (left < right) {
int pivotpos = QuickSort.partition(testArray, left, right);
QuickSort.quickSort(testArray, left, pivotpos - 1);
QuickSort.quickSort(testArray, pivotpos + 1, right);
}
return true;
}
public static int partition(int[] testArray, int low, int high) {
int i = low, j = high, pivot = testArray[low],temp=0;
while (i < j) {
while (i < j && testArray[j] >= pivot)
j--;
while (i < j && testArray[i] <= pivot)
i++;
temp = testArray[i];
testArray[i] = testArray[j];
testArray[j] = temp;
}
testArray[low] = testArray[i];
testArray[i] = pivot;
return i;
}
public static void main(String args[]) {
int[] testArray = new int[20];
QuickSort quickSort = new QuickSort();
quickSort.initTestArray(testArray);
System.out.println("排序前:");
quickSort.printTestArray(testArray);
if(!QuickSort.quickSort(testArray, 0, testArray.length - 1))
System.out.println("排序出錯!");
System.out.println("排序後:");
quickSort.printTestArray(testArray);
}
}