快速排序

思路:采用分治思想,每次划分时将该组的第一个数字作为轴值,划分后在该轴值左边的数均不大于该轴值,轴值右边的数均不小于该轴值。再递归划分轴值两边的组。

import java.util.*;
import static java.lang.System.*;

public class Main{
    static Scanner in = new Scanner(System.in);
    
    static int Partition(int a[],int first,int last)
    {
        int i=first,j=last;
        while(i<j)
        {
            while(i<j&&a[i]<=a[j]) j--;
            if(i<j)
            {
                int temp=a[i];
                a[i]=a[j];
                a[j]=temp;
                i++;
            }
            while(i<j&&a[i]<=a[j]) i++;
            if(i<j)
            {
                int temp=a[i];
                a[i]=a[j];
                a[j]=temp;
                j--;
            }
        }
        return i;
    }
    
    static void QuickSort(int a[],int first,int last)
    {
        if(first<last)
        {
            int pivot=Partition(a,first,last);
            QuickSort(a,first,pivot-1);
            QuickSort(a,pivot+1,last);
        }
    }
    
    public static void main(String[] args)
    {
        int a[] = {3,2,9,7,5,4};
        QuickSort(a,0,a.length-1);
        for(int elem:a)
            out.print(elem);
        out.println();
    }
}
原文地址:https://www.cnblogs.com/program-ccc/p/5324517.html