一.对数器的组成
1.随机生成数组函数lenRandomValueRandom
我们给该函数一个最大长度和最大数值,令其生成一个完全数据与长度随机的数组
public static int[] lenRandomValueRandom(int maxLen, int maxValue) {
int len = (int) (Math.random() * maxLen);
int ans[];
ans = new int[len];
for (int i = 0; i < len; i++) {
ans[i] = (int) (Math.random() * maxValue);
}
return ans;
}
注意进行int强制类型转换的时候一定要将后面所有的都用括号括起来
2.复制数组函数copy
public static int[] copy(int ans[]) {
int temp[];
temp = new int[ans.length];
for (int i = 0; i < ans.length; i++) {
temp[i] = ans[i];
}
return temp;
}
3.判断函数isSorted
以选择排序为例子,那么后面的数都比前面的数大;如果后面有一个数比前面的小,那么就退出循环并打印“选择排序错误”
public static boolean isSort(int ans[]) {
if (ans.length < 2) {
return true;
}
int max = ans[0];
for (int i = 0; i < ans.length; i++) {
if (max > ans[i]) {
return false;
}
max = Math.max(max, ans[i]);
}
return true;
}
4.主函数
主函数就是对数器的主要思路了
(1)先建立一个随机数组ans
(2)copy一个完全一样的数组temp
(3)进行10000次随机建立并isSort检测(也就是随机生成10000个例子),如果报错,那就打印该报错情况(通过temp备份数组来打印)
public static void main(String[] args) {
int maxLen = 100;
int maxValue = 1000;
int textTimes = 10000;
for (int i = 0; i < textTimes; i++) {
int ans[] = lenRandomValueRandom(maxLen, maxValue);
int temp[] = copy(ans);
sectionSort(ans);
if (!isSort(ans)) {
for (int j = 0; j < temp.length; j++) {
System.out.print(temp[j] + " ");
}
System.out.println();
System.out.println("选择排序错了!");
break;
}
}
}
二.对数器的应用场景
对数器可以实现引用大数据例子但是代码存在BUG用眼睛或小数据例子看不出来的情况
未来学习中会经常使用