作者:海鹰
本人才疏学浅,若有纰漏,虚心请教
本文讲述快速排序算法
版权所有,未经允许,请勿随意转载。
通过“交换”进行排序的方法,常见的有“冒泡排序”,以及基于冒泡的“快速排序”。
冒泡排序(Bubble Sort)
示例代码 [Java] :1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17/**
* 冒泡排序
* @param nums
* @return
*/
public int[] bubbleSort(int[] nums){
for( int i=0; i<nums.length-1; i++ ){
for( int j=1, temple; j<nums.length-i; j++ ){
if( nums[j-1] > nums[j] ){
temple = nums[j-1];
nums[j-1] = nums[j];
nums[j] = temple;
}
}
}
return nums;
}
快速排序(Quick Sort)
快速排序是对冒泡排序的一种改进。它的基本思想是,通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序。
示例代码 [Java] :1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37/**
*
* @param nums
* @param low
* @param high
* @return
*/
public int partition(int[] nums, int low, int high){
int pivotKey = nums[low];
while ( low < high ){
while( low < high && nums[high] >= pivotKey ){
high--;
}
nums[low] = nums[high];
while( low < high && nums[low] <= pivotKey ){
low++;
}
nums[high] = nums[low];
}
nums[low] = pivotKey;
return low;
}
/**
* 快速排序
* @param nums
* @param low
* @param high
*/
public void quickSort(int[] nums, int low, int high){
int pivotLoc;
if( low < high ){
pivotLoc = partition(nums, low, high);
quickSort(nums, low, pivotLoc - 1 );
quickSort(nums, pivotLoc + 1, high);
}
}