gpt4 book ai didi

javascript - 无法将数组作为 javascript 函数的参数传递

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:06:11 26 4
gpt4 key购买 nike

我试图在 javascript 中实现快速排序算法,我必须从一个 txt 文件中提取 10,000 个数字,将它们传递到一个数组中,然后使用 nodejs 的 fs 模块将其作为我的快速排序函数的参数传递。该代码能够读取 10,000 个数字,并将它们从字符串数组转换为数字数组,但是当我尝试将数组传递到我的函数时,只传递了 3472 个数字,我不明白。

const fs = require('fs');

// Reading the data from the file containing the 10,000 numbers
const file = fs.readFileSync('./quickSort.txt', 'utf-8');

//Checking if it has read all the numbers correctly
console.log(file); // Displays the 10,000 numbers as strings in an array

// Convert them from string to integer
const finalFile = file.split('\n').map(e => {
return parseInt(e, 10);
})

// Checking if it has converted each element of the array to an integer
//console.log(finalFile) displays the array, with the 10,000 elements converted to integers

// Initialize a counter for the comparaisons made by the quickSort algorithm
let comparisons = 0;

// Sort them using quick sort
function quick_Sort(origArray) {

if (origArray.length <= 1) {
return origArray;
} else {
// Checking if the array has been correctly passed as an argument
console.log(origArray.length); //Displays 3742 instead of 10,000
var left = [];
var right = [];
var newArray = [];
var pivot = origArray.pop();
var length = origArray.length;
// I have tried comparisons += length - 1; too, but i doesn't work
comparisons += length;
for (var i = 0; i < length; i++) {
if (origArray[i] <= pivot) {
left.push(origArray[i]);

} else {
right.push(origArray[i]);
}
}

for (var i = 0; i < right.length; i++) {
comparisons++;
if (right[i] < pivot) {
return right.splice(i, 0, pivot);
}
}

return newArray.concat(quick_Sort(left), quick_Sort(right));
}
}

// Display the result
const result = quick_Sort(finalFile);

// expected output: 25
console.log(result);

非常感谢。

编辑:实际上大小的问题来自函数的最后一个 for 循环,如果我删除它,并在其中插入枢轴,它就可以工作(感谢 StardustGogeta):

return newArray.concat(quick_Sort(left), pivot, quick_Sort(right));

最佳答案

这是一个逻辑错误。你需要改变

return newArray.concat(quick_Sort(left), quick_Sort(right));

return newArray.concat(quick_Sort(left), pivot, quick_Sort(right));

有了这个改变,这个程序对我有用。问题是您在排序过程中不小心删除了(通过 .pop())大约 1/3 的输入值(pivot 值)。

关于javascript - 无法将数组作为 javascript 函数的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57312575/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com