快速排序

java版

/************************************************

File Name: QuickSort.java
Author: lxm
Created Time: 2016年04月27日 星期三 18时52分51秒
**********************************************/

public class QuickSort
{
private static final int N = 10;
public static void main(String[] args)
{
int[] a = {6,1,2,7,9,3,4,5,10,8};
quickSort(a,0,N-1);
printArray(a);
}

public static void printArray(int[] a)
{
    for(int item:a)
    {
        System.out.printf("%d	",item);
    }
    System.out.println();
}
public static void quickSort(int[] a, int low, int high)
{
    if(low>=high)
    {
        return;
    }
    int key = partition(a,low,high);
    quickSort(a,0,key-1);
    quickSort(a,key+1,high);
}

public static int partition(int[] a,int low, int high)
{
    int temp = a[low];
    while(low<high)
    {
        while(low<high && a[high]>=temp)
        {
            --high;
        }
        a[low] = a[high];

        while(low<high && a[low]<=temp)
        {
            ++low;
        }
        a[high] = a[low];
    }

    a[low] = temp;

    return low;
}

}

···

C版本

#include<stdio.h>
#define N 10

int partition(int* a,int low, int high);
void quickSort(int* a,int low,int high);
void printArray(int* a,int n);

int main(void)
{
    int a[N] = {6,1,2,7,9,3,4,5,10,8};
    quickSort(a,0,N-1);
//  int k = partition(a,0,9);
//  printf("%d
",k);
    printArray(a,N);
    return 0;
}
int partition(int* a,int low, int high)
{

    int temp = a[low];
    while(low<high)
    {
        while(low<high && a[high]>=temp)
        {
            high--;
        }
        a[low] = a[high];

        while(low<high && a[low]<=temp)
        {
            ++low;
        }
        a[high] = a[low];
    }
    a[low] = temp;

    return low;
}

void quickSort(int* a,int low,int high)
{
    if(low>=high)
    {
        return ;
    }
    int key = partition(a,low,high);
    quickSort(a,0,key-1);
    quickSort(a,key+1,high);
}
void printArray(int* a,int n)
{
    int i;
    for(i=0;i<n;++i)
    {
        printf("%d	",a[i]);
    }
    printf("
");
}
原文地址:https://www.cnblogs.com/yldf/p/6249911.html