【发布时间】:2019-08-01 15:39:19
【问题描述】:
我正在尝试在 javascript 中实现 quickSort 算法,我必须从 txt 文件中提取 10,000 个数字,将它们传递到一个数组中,然后使用 nodejs 的 fs 模块将其作为我的 quickSort 函数的参数传递。该代码能够读取 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));
【问题讨论】:
-
错误是什么?也许执行时间有问题?是否可能需要超过定义的超时时间?
-
您绝对确定 finalFile 有 10000 行吗?使用正确大小的数组时,我无法复制此问题。 (你能把你正在测试的文件给我们吗?)
-
@StardustGogeta 你好,谢谢你的帮助,我已经把文件贴在这里了github.com/HugoDouma/quickSort。
-
@Kacper 您好,感谢您的帮助,我在播放代码时没有任何错误显示,我只有输入 3742 个数字,因为 originArray 的长度只有 3742数字(我在函数内使用 console.log 进行了检查)。
标签: javascript node.js algorithm quicksort