assert isSorted( arr );
以上这句在 false 时,并不抛异常,没有阻断程序执行,程序正常结束。
throw new RuntimeException("isSorted : false"); 或者 throw new Error("isSorted : false"); 可以抛异常并阻断程序运行
public static boolean isSorted(Comparable[] arr){
for(int i=0; i<arr.length-1; i++){
if( arr[i].compareTo(arr[i+1]) > 0){
return false;
}
}
return true;
}
public static void testSort(ISort sortInstance, Comparable[] arr){
long begin = System.currentTimeMillis();
sortInstance.sort(arr);
long end = System.currentTimeMillis();
// assert isSorted(arr);
if(!isSorted(arr)){
throw new Error("isSorted : false");
// throw new RuntimeException("isSorted : false");
}
System.out.println(String.format("%s : %s ms", sortInstance.getClass().getSimpleName(), (end - begin)));
}用了个自定义接口(与问题无关)
public interface ISort<T extends Comparable> {
void sort(T[] arr);
}主要是这个代码
public class InsertionSortV2<T extends Comparable> implements ISort<T> {
@Override
public void sort(T[] arr) {
for(int i=1; i<arr.length; i++){
T e = arr[i]; // 将 i 位置的元素保存在 e 中。
int j ; // 保存元素 e 应该插入的位置
for(j=i; j>0; j--){
if(arr[j-1].compareTo(arr[j]) > 0){
// if(arr[j-1].compareTo( e ) > 0){
arr[j] = arr[j-1];
}else{
break;
}
}
arr[j] = e; // 这里 不可以直接写 arr[j] = arr[i];
}
}
public static void main(String[] args) {
InsertionSortV2<Integer> is = new InsertionSortV2<>();
int n = 10;
Integer[] intArr = SortTestHelper.generateRandomArray(n, 0, 1000);
SortTestHelper.printArray(intArr);
SortTestHelper.testSort(is, intArr);
SortTestHelper.printArray(intArr);
// SortTestHelper.printArray(intArr);
// is.sort(intArr);
// SortTestHelper.printArray(intArr);
}
}第 8 行 是错误的写法,但是
如果用 assert 在main中不打印下排序前后的数组,会误以为排序是成功的。