zoukankan      html  css  js  c++  java
  • Algs4-2.1.16验证排序是否正确并且未修改

     2.1.16验证。编写一个check()方法,调用sort()对任意数组排序。如果排序成功而且数组中的所有对象均没有被修改则返回true,否则返回false。不要假设sort()只能通过exch()来移动数据,可以信任并使用Array.sort()。
    答:在check中将原数组复制一份,然后用sort对原数组进行排序,然后用Array.sort对数组复本排序,然后对比两个排序后的数组元素,全部对应元素相同时返回true,遇到不相同时返回false。
    import java.util.Arrays;
    public class Example
    {
        public static void sort(Comparable[] a)
        {
        }
       
        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=0;i<a.length;i++)
                if(less(a[i],a[i-1])) return false;
            return true;
        }
       
        public static boolean check(Comparable[] a)
        {
            //create a clone array of a
            Comparable[] aClone=new Comparable[a.length];
            for(int i=0;i<a.length;i++)
                aClone[i]=a[i];
            //sort a
            sort(a);
            //sort aClone
            Arrays.sort(aClone);
            //compare array a and aClone
            for(int i=0;i<a.length;i++)
                if (a[i] !=aClone[i]) return false;
            return true;
        }
    }

  • 相关阅读:
    设计模式读书笔记之工厂方法模式
    设计模式读书笔记之简单工厂
    SortedList 键值 不排列 无序
    ASPxGridView 列类型
    MVC3 Razor一些注意
    nvarchar(MAX)的长度
    C#转换运算符explicit和implicit
    ASPxGridView 模糊过滤 查询(二)
    Direct3D渲染管线简介
    Unity3D学习之路 C#学习笔记(一)
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9860028.html
Copyright © 2011-2022 走看看