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

2.1.1

时间:2018-05-29 15:31:29      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:answer   return   .com   rabl   str   for   ati   als   false   

question:

Show, in the style of example trace with ALGORITHM 2.1, how selection sort sorts the array E A S Y Q U E S T I O N.

answer:

//我刚开时居然手写

import edu.princeton.cs.algs4.*;

public class Selection
{
    public static void sort(Comparable[] a)
    {
        int N = a.length;
        for(int i = 0; i < N; i++)
        {
            int min = i;
            for(int j = i+1; j < N; j++)
                if(less(a[j], a[min])) min = j;
            StdOut.print(i + " " + min + "\t");
            for(int t = 0; t < a.length; t++)
                StdOut.print(a[t] + " ");
            StdOut.println();
            
            exch(a,i,min);
        }
    }
    
    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;
    }
    
    private static void show(Comparable[] a)
    {
        for(int i = 0; i < a.length; i++)
            StdOut.print(a[i] + " ");
        StdOut.println();
    }
    
    public static boolean isSorted(Comparable[] a)
    {
        for(int i = 1; i < a.length; i++)
            if(less(a[i], a[i-1])) return false;
        return true;
    }
    
    public static void main(String[] args)
    {
        //输入 E A S Y Q U E S T I O N
        String[] a = In.readStrings();//CTRL + d
        sort(a);
        assert isSorted(a);
        show(a);
    }
}

 

2.1.1

标签:answer   return   .com   rabl   str   for   ati   als   false   

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

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