本文根据《大话数据结构》一书,实现了Java版的快速排序。
更多:数据结构与算法合集
基本概念
基本思想:在每轮排序中,选取一个基准元素,其他元素中比基准元素小的排到数列的一边,大的排到数列的另一边;之后对两边的数列继续进行这种排序,最终达到整体有序。
图片来自公众号:程序员小灰
实现代码
根据上述基本思想,可以先写出快速排序最核心的代码:对于数组a中从下标为low至下标为high的元素,选取一个基准元素(记为pivotKey),根据与基准比较的大小,将这些元素排到基准元素的两端。
注意点:1.两端向中间扫描时,一定要先从高段往低端扫描(low<high && a[high]<pivotKey),这样才能实现pivotKey一直会交换到中间。!!
2.比较大小时不要忘记low<high还要一直成立,即(low<high && a[high]<pivotKey)。!! 例如,数组全为同一个数字时,不加这个判断有可能导致越界
/**
* 对数组a中下标从low到high的元素,选取基准元素pivotKey,
* 根据与基准比较的大小,将各个元素排到基准元素的两端。
* 返回值为最后基准元素的位置
*/
public int partition(int[] a, int low, int high) {
int pivotKey = a[low]; //用第一个元素作为基准元素
while (low < high) { //两侧交替向中间扫描
while (low < high && a[high] >= pivotKey)
high--;
swap(a, low, high); //比基准小的元素放到低端
while (low < high && a[low] <= pivotKey)
low++;
swap(a, low, high); //比基准大的元素放到高端
}
return low; //返回基准元素所在位置
}
将元素分为两部分后,必须对两个子部分继续进行上面的排序,所以要用到递归。代码如下:
/**
* 递归调用
*/
public void qSort(int[] a, int low, int high) {
int pivot;
if (low >= high)
return;
pivot = partition(a, low, high); //将数列一分为二
qSort(a, low, pivot - 1); //对低子表排序
qSort(a, pivot + 1, high); //对高子表排序
}
完整Java代码
(含测试代码)
import java.util.Arrays;
/**
*
* @Description 快速排序
*
* @author yongh
* @date 2018年9月14日 下午2:39:00
*/
public class QuickSort {
public void quickSort(int[] a) {
if (a == null)
return;
qSort(a, 0, a.length - 1);
}
/**
* 递归调用
*/
public void qSort(int[] a, int low, int high) {
int pivot;
if (low >= high)
return;
pivot = partition(a, low, high); //将数列一分为二
qSort(a, low, pivot - 1); //对低子表排序
qSort(a, pivot + 1, high); //对高子表排序
}
/**
* 对数组a中下标从low到high的元素,选取基准元素pivotKey,
* 根据与基准比较的大小,将各个元素排到基准元素的两端。
* 返回值为最后基准元素的位置
*/
public int partition(int[] a, int low, int high) {
int pivotKey = a[low]; //用第一个元素作为基准元素
while (low < high) { //两侧交替向中间扫描
while (low < high && a[high] >= pivotKey)
high--;
swap(a, low, high); //比基准小的元素放到低端
while (low < high && a[low] <= pivotKey)
low++;
swap(a, low, high); //比基准大的元素放到高端
}
return low; //返回基准元素所在位置
}
public void swap(int[] a, int i, int j) {
int temp;
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
// =========测试代码=======
public void test1() {
int[] a = null;
quickSort(a);
System.out.println(Arrays.toString(a));
}
public void test2() {
int[] a = {};
quickSort(a);
System.out.println(Arrays.toString(a));
}
public void test3() {
int[] a = { 1 };
quickSort(a);
System.out.println(Arrays.toString(a));
}
public void test4() {
int[] a = { 3, 3, 3, 3, 3 };
quickSort(a);
System.out.println(Arrays.toString(a));
}
public void test5() {
int[] a = { -3, 6, 3, 1, 3, 7, 5, 6, 2 };
quickSort(a);
System.out.println(Arrays.toString(a));
}
public static void main(String[] args) {
QuickSort demo = new QuickSort();
demo.test1();
demo.test2();
demo.test3();
demo.test4();
demo.test5();
}
}
null [] [1] [3, 3, 3, 3, 3] [-3, 1, 2, 3, 3, 5, 6, 6, 7]