快速排序是C.R.A.Hoare于1962年提出的一种划分交换排序。它采用了一种分治的策略,通常称其为分治法(Divide-and-ConquerMethod)。
该方法的基本思想是:
1.先从数列中取出一个数作为基准数。
2.分区过程,将比这个数大的数全放到它的右边,小于或等于它的数全放到它的左边。
3.再对左右区间重复第二步,直到各区间只有一个数。
<span style="font-size:18px;">int Partition(SqList *L,int low,int high)
{
int pivotkey;
pivotkey=L->r[low]; /* 用子表的第一个记录作枢轴记录 */
while(low<high) /* 从表的两端交替地向中间扫描 */
{
while(low<high&&L->r[high]>=pivotkey)
high--;
swap(L,low,high);/* 将比枢轴记录小的记录交换到低端 */
while(low<high&&L->r[low]<=pivotkey)
low++;
swap(L,low,high);/* 将比枢轴记录大的记录交换到高端 */
}
return low; /* 返回枢轴所在位置 */
}
/* 对顺序表L中的子序列L->r[low..high]作快速排序 */
void QSort(SqList *L,int low,int high)
{
int pivot;
if(low<high)
{
pivot=Partition(L,low,high); /* 将L->r[low..high]一分为二,算出枢轴值pivot */
QSort(L,low,pivot-1);/* 对低子表递归排序 */
QSort(L,pivot+1,high);/* 对高子表递归排序 */
}
}
/* 对顺序表L作快速排序 */
void QuickSort(SqList *L)
{
QSort(L,1,L->length);
}</span>
#include<stdio.h>
int partition(int a[],int left,int right)
{
int i=left;
int j=right;
int temp=a[i];
while(i<j)
{
while(i<j && a[j]>=temp)
j--;
if(i<j)
a[i]=a[j];
while(i<j && a[i]<=temp)
i++;
if(i<j)
a[j]=a[i];
}
a[i]=temp;
return i;
}
void quickSort(int a[],int left,int right)
{
int dp;
if(left<right)
{
dp=partition(a,left,right);
quickSort(a,left,dp-1);
quickSort(a,dp+1,right);
}
}
int main()
{
int a[9]={5,4,9,1,7,6,2,3,8};
quickSort(a,0,8);
for(int i=0;i<9;i++)
{
printf("%d ",a[i]);
}
return 0;
}
Java版本:
package algorithm;
import java.util.Arrays;
public class QuickSort {
public static void qsort(int[] a, int low, int high) {
int pivot;
if (low < high) {
pivot = partition(a, low, high);
qsort(a, low, pivot-1);
qsort(a, pivot+1, high);
}
}
public static int partition(int[] a, int low, int high) {
int pivotkey = a[low];
int tmp;
while (low < high) {
while (low < high && a[high] >= pivotkey) {
high--;
}
if(low<high){
tmp = a[low];
a[low] = a[high];
a[high] = tmp;
}
while (low < high && a[low] <= pivotkey) {
low++;
}
if(low<high){
tmp = a[low];
a[low] = a[high];
a[high] = tmp;
}
}
return low;
}
public static void main(String[] args) {
int[] a = {5, 4,11, 7,9,2};
QuickSort.qsort(a, 0, 5);
System.out.println(Arrays.toString(a));
}
}