/** * 排序算法测试 */ /** * 创建一个随机数数组 * @returns */ function getRandomData(count = 20) { var randomData = [] for (let i = 0; i < count; i++) // 生成随机数 randomData.push(Math.ceil(Math.random() * 100 - 50)) return randomData } var data = [ [], [-1], [1, 2], [1, 2, 3, 4, 5, 6, 7, 8], [8, 7, 6, 5, 4, 3, 2, 1], [1, 1, 1, 1, 1, 1, 1], [5, 8, 7, 4, 3, 1, 6, 2, 6, 5], [47, 11, 50, 13, 16, 49, 8, 9, 38, 27, 20], // getRandomData(6), ] var check = [ [], [-1], [1, 2], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 1, 1, 1, 1, 1, 1], [1, 2, 3, 4, 5, 5, 6, 6, 7, 8], [8, 9, 11, 13, 16, 20, 27, 38, 47, 49, 50], // null ] var sortAlgorithm = { quicksort: new QuickSort(animation), bubblesort: new BubbleSort(animation), selectionSort: new SelectionSort(animation), insertionSort: new InsertionSort(animation), } // 遍历每一种算法 Object.values(sortAlgorithm).forEach(sortAlgo => { // 输出调试信息 console.log("算法信息", sortAlgo.info()) data.forEach(element => { // 将数组元素进行深拷贝 var input = JSON.parse(JSON.stringify(element)) // 进行排序 var result = sortAlgo.sort(input) console.log("before", element, "after", result) // 与结果进行对比,判断是否正确 if (data.indexOf(element) > -1) { var rightSortResult = check[data.indexOf(element)]; if (rightSortResult) { if (JSON.stringify(rightSortResult) !== JSON.stringify(result)) { console.warn("👆结果不匹配!正确结果为", rightSortResult) } else { console.info("👆正确") } } else { console.log("👆缺少正确答案,跳过") } } }); // 输出一个空行,便于观察 console.log("-----------------------------------------------") });