它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。(来自百度百科)
实现程序:
/** * Copyright (c) 2011 Trusted Software and Mobile Computing(TSMC) * All rights reserved. * Author: Jarg Yee <[email protected]> * http://jarg.iteye.com/ */ import static java.lang.System.out; /* * 交换排序: 1. 冒泡排序 2. 快速排序 * 实现快速排序 */ public class QSort { /* 待排序元素 */ private static int[] a = {3,1,3,2,9,8,1,2,4}; private static int[] b = a.clone(); // 拷贝一份a中数据到b /* for debugging. */ public static void main(String[] args) { qSort(0,a.length-1); // 排序 display(); // 显示排序结果 } /* 快速排序 */ public static void qSort(int beginIndex,int endIndex) { if(beginIndex<endIndex) { int q = partition(beginIndex,endIndex); // 分割点索引值 qSort(beginIndex,q-1); // 分治,对分割点q左半边快速排序 qSort(q+1,endIndex); // 分治,对分割点q右半边快速排序 } } /* 划分,从而分治 找出分割点索引值 */ public static int partition(int beginIndex,int endIndex) { int x = a[beginIndex]; // 以当前待排序元素中第一个点为基准. /* 设置二个索引,分别指向当前待排序元素头和尾 */ int i = beginIndex,j = endIndex; while(i<j) { if(a[i]<=a[j]) { // 大于基准的元素 /* 修改索引位置 */ // 指向基准点的索引不变 // 另一个索引变化,向指向基准点的索引指向位置靠近 if(a[i] == x) j--; else i++; } else { // 交换,小于基准的元素与基准交换位置 int temp = a[i]; a[i] = a[j]; a[j] = temp; /* 修改索引位置 */ if(a[i] == x) j--; else i++; } } return j; // 此时i=j,返回i或者j都可以 } /* 输出待排序元素 */ public static void display() { out.print("排序前:"); for(int value : b) { out.print("\t" + value); } out.println("\n-------------------------------------------"); out.print("排序后:"); for(int value : a) { out.print("\t" + value); } } }