简述快速排序
快速排序是对冒泡排序的一种改进, 它是不稳定的。由C. A. R. Hoare在1962年提出的一种划分交换排序,采用的是分治策略(一般与递归结合使用),以减少排序过程中的比较次数,它的最好情况为O(nlogn),最坏情况为O(n^2),平均时间复杂度为O(nlogn)。
基本思想:选择一个基准数,通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小。然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以达到全部数据变成有序。
实现代码
/**
*********************
* Quick sort recursively.
*
* @param paraStart The start index.
* @Param paraEnd The end index.
*********************
*/
public void quickSortRecursive(int paraStart, int paraEnd) {
// Nothing to sort.
if (paraStart >= paraEnd) {
return;
} // Of if
int tempPivot = data[paraEnd].key;
DataNode tempNodeForSwap;
int tempLeft = paraStart;
int tempRight = paraEnd - 1;
// Find the position for the pivot.
// At the same time move smaller elements to the left and bigger one to the
// right.
while (true) {
while ((data[tempLeft].key < tempPivot) && (tempLeft < tempRight)) {
tempLeft++;
} // Of while
while((data[tempRight].key >= tempPivot) && (tempLeft < tempRight)){
tempRight--;
}// Of while
if (tempLeft < tempRight) {
// Swap.
System.out.println("Swapping" + tempLeft + "and" + tempRight);
tempNodeForSwap = data[tempLeft];
data[tempLeft] = data[tempRight];
data[tempRight] = tempNodeForSwap;
} else {
break;
} // Of if
} // Of while
// Swap
if (data[tempLeft].key > tempPivot) {
tempNodeForSwap = data[paraEnd];
data[paraEnd] = data[tempLeft];
data[tempLeft] = tempNodeForSwap;
} else {
tempLeft++;
} // Of if
System.out.println("From " + paraStart + "to " + paraEnd + ": ");
System.out.println(this);
quickSortRecursive(paraStart, tempLeft - 1);
quickSortRecursive(tempLeft + 1, paraEnd);
}// Of quickSortRecursive
/**
*********************
* Quick sort.
*********************
*/
public void quickSort() {
quickSortRecursive(0, length - 1);
}// Of quickSort
/**
*********************
* Test the method
*********************
*/
public static void quickSortTest() {
int[] tempUnsortedKeys = { 1, 3, 12, 10, 5, 7, 9 };
String[] tempContents = { "if", "then", "else", "switch", "case", "for", "while" };
DataArray tempDataArray = new DataArray(tempUnsortedKeys, tempContents);
System.out.println(tempDataArray);
tempDataArray.quickSort();
System.out.println("Result\r\n" + tempDataArray);
}// Of quickSortTest
2.读入数据
代码如下(示例):
-------quickSortTest-------
I am a data array with 7 items.
(1, if) (3, then) (12, else) (10, switch) (5, case) (7, for) (9, while)
Swapping2and5
Swapping3and4
From 0to 6:
I am a data array with 7 items.
(1, if) (3, then) (7, for) (5, case) (9, while) (12, else) (10, switch)
From 0to 3:
I am a data array with 7 items.
(1, if) (3, then) (5, case) (7, for) (9, while) (12, else) (10, switch)
From 0to 1:
I am a data array with 7 items.
(1, if) (3, then) (5, case) (7, for) (9, while) (12, else) (10, switch)
From 5to 6:
I am a data array with 7 items.
(1, if) (3, then) (5, case) (7, for) (9, while) (10, switch) (12, else)
Result
I am a data array with 7 items.
(1, if) (3, then) (5, case) (7, for) (9, while) (10, switch) (12, else)
ps:这篇文章的图片也太cute了吧
链接: link.