码迷,mamicode.com
首页 > 其他好文 > 详细

2.3.2

时间:2018-06-03 16:22:49      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:answer   shuffle   ble   exe   std   void   private   3.2   --   

question:

Show, in the style of the quicksort trace given in this section, how quicksort sorts the array E A S Y Q U E S T I O N (for the purpose of this exercise, ignore the initial shuffle).

answer:

import edu.princeton.cs.algs4.*;

public class Quicksort
{
    private static boolean less(Comparable v, Comparable w)
    {
        return v.compareTo(w) < 0;
    }
    
    private static void exch(Comparable[] a, int i, int j)
    {
        Comparable t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
    
    public static int partition(Comparable[] a, int lo, int hi)
    {
        Comparable v = a[lo];//应该是a[lo]而不是a[0]
        int i = lo, j = hi + 1;
        while(true)
        {
            while(less(a[++i],v))
            {
                if(i >= hi)
                    break;
            }
            while(less(v,a[--j]))
            {
                if(j <= lo)
                    break;
            }
            if(i >= j)
                break;
            exch(a,i,j);
        }
        exch(a,lo,j);
        if(lo == hi)
            StdOut.printf("%3d     % 3d ", lo, hi);
        else
            StdOut.printf("%3d %3d % 3d ", lo, j, hi);
        show(a);
        return j;
    }
    
    public static void sort(Comparable[] a)
    {
       // StdRandom.shuffle(a);
        sort(a, 0, a.length-1);
    }

    public static void sort(Comparable[] a, int lo, int hi)
    {
        if(lo > hi)
            return;
        int mid = partition(a,lo,hi);
        sort(a,lo,mid-1);
        sort(a,mid+1,hi);
    }
    
    public static void show(Comparable[] a)
    {
        for(Comparable i: a)
            StdOut.print(i + " ");
        StdOut.println();
    }
    
    public static void main(String[] args)
    {
        //E A S Y Q U E S T I O N
        String[] a = In.readStrings();
        sort(a);
        StdOut.print("            ");
        show(a);
    }
}

 

2.3.2

标签:answer   shuffle   ble   exe   std   void   private   3.2   --   

原文地址:https://www.cnblogs.com/w-j-c/p/9129361.html

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