码迷,mamicode.com
首页 > 编程语言 > 详细

快速排序

时间:2016-03-27 01:32:53      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

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

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();
    }
}

 

快速排序

标签:

原文地址:http://www.cnblogs.com/program-ccc/p/5324517.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!