question:
Certification. Write a check() method that call sort() for a given array and returns true if sort() puts the array in order and leaves the same set of objects in the array as were there initially, false otherwise. Do
answer:
//判断长度是否相等,排序是否正确,排序前数组每个元素的个数与在排序后数组中该元素个数是否相等
import edu.princeton.cs.algs4.*; import java.util.Arrays; public class Certification { public static boolean check(Comparable[] a) { Comparable[] b = new Comparable[a.length]; System.arraycopy(a,0,b,0,a.length);//复制数组 Arrays.sort(a); //a[0] = 10.0;用于判断 for(int i = 1; i < a.length; i++)//排序正确性检测 { if(a[i].compareTo(a[i-1])<0) return false; } if(a.length != b.length)//长度检测 return false; for(int i = 0; i < b.length; i++) { int num1 = 0; int num2 = 0; for(int j = 0; j < b.length; j++)//计算原数组中与第i个元素相同的个数 { if(b[j]==b[i]) num1++; } for(int j = 0; j < a.length; j++)//计算排序后数组中与第i个元素相同的个数 { if(a[j]==b[i]) num2++; } if(num1 != num2) return false; } return true; } public static void main(String[] args) { String[] a = In.readStrings(); if(check(a) == true) StdOut.println("no problem"); else StdOut.println("wrong"); } }