通用工具类
最后更新于:2022-08-17 15:31:04
所有的数据结构的相关工具类,都在此文中进行统计
ArrayGenerator
创建出随机或有序的数组
public class ArrayGenerator {
private ArrayGenerator() {
}
public static Integer[] generatorOrderArray(int n) {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++) {
arr[i] = i;
}
return arr;
}
public static Integer[] generatorRandomArray(int n, int bound) {
Integer[] arr = new Integer[n];
Random rnd = new Random();
for (int i = 0; i < n; i++) {
arr[i] = rnd.nextInt(bound);
}
return arr;
}
}
各种排序算法的调用类
public class SortHelper {
private SortHelper() {
}
public static > boolean isSorted(T[] arr) {
for (int i = 1; i < arr.length; i++) {
if (arr[i - 1].compareTo(arr[i]) == 1) {
return false;
}
}
return true;
}
public static > void sortTest(String sortName, T[] arr) {
long startTime = System.nanoTime();
if (sortName.equals("SelectionSort")) {
SelectSort.ASC(arr);
} else if (sortName.equals("InsertingSort")) {
InsertingSort.sort(arr);
} else if (sortName.equals("MergeSort")) {
MergeSort.sort(arr);
} else if (sortName.equals("MergeSortBU")) {
MergeSort.sortBU(arr);
} else if (sortName.equals("QuickSort")) {
QuickSort.sort(arr);
} else if (sortName.equals("QuickSort2")) {
QuickSort.sort2ways(arr);
} else if (sortName.equals("QuickSort3")) {
QuickSort.sort3ways(arr);
} else if (sortName.equals("HeapSort")) {
HeapSort.sort(arr);
} else if (sortName.equals("HeapSort2")) {
HeapSort.sort2(arr);
} else if (sortName.equals("BubbleSort")) {
BubbleSort.sort(arr);
} else if (sortName.equals("BubbleSort3")) {
BubbleSort.sort3(arr);
} else if (sortName.equals("ShellSort")) {
ShellSort.sort(arr);
} else if (sortName.equals("ShellSort2")) {
ShellSort.sort2(arr);
}
long endTime = System.nanoTime();
double time = (endTime - startTime) / 1000000000.0;
if (!isSorted(arr)) {
throw new RuntimeException(sortName + " failed");
}
System.out.println(String.format("%s,n = %d : %f s", sortName, arr.length, time));
}
}