1.对数器作用
解决某个算法问题时,已知一个较高复杂度的算法(可能是暴力解法),判断某个较低复杂度的算法是否正确。
2.实现思路
- 先实现一个随机数组生成器,生成指定范围内随机长度,随机数值的数组
- 然后将原数组复制一份
- 原数组用较高复杂度算法测,复制数组用较低复杂度算法测
- 判断两次的结果是否一致
随机数组生成器分析:
Math.random()是[0,1)范围的一个随机数,所以(N+1)*Math.random()是[0,N+1)的一个随机数,再取整,就是[0,N]范围的一个随机数。
(int) ((N + 1) * Math.random())范围在[0,N],(int) (N * Math.random())范围在[0,N-1],所以相减之后是一个范围在[-N-1,N]的随机数
3.代码实现
public class Logarithm {
public static void main(String[] args) {
int testTime = 500000;
int maxSize = 20;
int maxValue = 20;
boolean succeed = true;
for (int i = 0; i < testTime; i++) {
int[] arr1 = generateRandomArray(maxSize, maxValue);
int[] arr2 = copy(arr1);
bubbleSort(arr1);
qsort(arr2,0,arr2.length-1);
if (!isEqual(arr1, arr2)) {
succeed = false;
System.out.println(Arrays.stream(arr1).boxed().collect(Collectors.toList()));
System.out.println(Arrays.stream(arr2).boxed().collect(Collectors.toList()));
break;
}
}
System.out.println(succeed ? "算法测试成功!" : "失败!");
}
//随机数组生成器
public static int[] generateRandomArray(int maxSize, int maxValue) {
int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
for (int i=0;i<arr.length;i++) {
arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
}
return arr;
}
//判断两数组是否完全相等
public static boolean isEqual(int[] arr1, int[] arr2) {
if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) {
return false;
}
if (arr1 == null && arr2 == null) {
return true;
}
if (arr1.length != arr2.length) {
return false;
}
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i]) {
return false;
}
}
return true;
}
//复制数组
public static int[] copy(int[] arr) {
if (arr == null || arr.length == 0) return new int[0];
int[] res = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
res[i] = arr[i];
}
return res;
}
//冒泡排序
private static void bubbleSort(int[] nums) {
int n = nums.length;
for (int i = 0; i < n - 1; i++) {
for (int j = n - 1; j >= i + 1; j--) {
if (nums[j] < nums[j - 1]) {
swap(nums, j, j - 1);
}
}
}
}
//快速排序
private static void qsort(int[] nums, int low, int high) {
if (low < high) {
int povit = partition(nums, low, high);
qsort(nums, low, povit - 1);
qsort(nums, povit + 1, high);
}
}
private static int partition(int[] nums, int low, int high) {
int povitkey = nums[low];
while (low < high) {
while (low < high && povitkey <= nums[high]) high--;
swap(nums, low, high);
while (low < high && povitkey >= nums[low]) low++;
swap(nums, low, high);
}
return low;
}
private static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
4.测试
直接运行:
当把快排实现的第二个swap去掉,运行: