我正在尝试构建一个排序可视化器,当我编写合并排序算法时,返回数组的长度始终为1,而我的算法看起来也很好,我不知道是什么原因使它返回了单个长度数组元素,所以我尝试了使用控制台语句进行调试,直到递归为止,一切似乎都很好。
我的主要app.js代码在这里:
testSortingAlgo() {
//here we are creating 100 arrays for checking the sorting algorithms
for (let i = 0; i < 100; i++) {
const array = [];
//creating different lengths of the array
const length = randomIntFromInterval(1, 1000);
console.log(length);
for (let j = 0; j < length; j++) {
//push all collection of negative and positive numbers
array.push(randomIntFromInterval(-1000, 1000));
}
console.log(array.length);
console.log(array.slice().length);
//for sorting in javascript inbuilt function .we are passing (a, b) => (a - b) because inbult function
// checks from starting character so in case of (200,5) 5 is greater as first char of 5 is greater than
// first char of 200 that is 2
const javascriptSortedArray = array.slice().sort((a, b) => (a - b))
const SortedArray = sortingAlgorithms.mergeSort(array.slice());
console.log(arraysAreEqual(javascriptSortedArray, SortedArray));
}
}
在此功能中,我正在检查排序算法的有效性。当我将传递array.slice()
给合并排序时。数组在以下代码中被操纵
export const mergeSort = array => {
// for (let i = 0; i < array.length; i++) {
// console.log(array[i]);
if (array.length <= 1) return array;
const middleIdx = Math.floor(array.length / 2);
const firstHalf = mergeSort(array.slice(0, middleIdx));
const secondHalf = mergeSort(array.slice(middleIdx, array.length));
const sortedArray = [];
let i = 0, j = 0;
while (i < firstHalf.length && j < secondHalf.length) {
if (firstHalf[i] < secondHalf[j]) {
sortedArray.push(firstHalf[i++]);
} else {
sortedArray.push(secondHalf[j++]);
}
}
while (i < firstHalf.length) array.push(firstHalf[i++]);
while (j < secondHalf.length) array.push(secondHalf[j++]);
return sortedArray;
}
它返回一个数组元素。
我认为您会为此而努力,过去我已经做过很多次了。
while(i<firstHalf.length) array.push(firstHalf[i++]);
while(j<secondHalf.length) array.push(secondHalf[j++]);
我想你打算 sortedArray
在这个repl https://repl.it/repls/BisqueNewMultitasking#index.js上工作
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句