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

时间:2019-08-01 15:39:19

标签: javascript node.js algorithm quicksort

我正在尝试在javascript中实现quickSort算法,我必须使用nodejs的fs模块从txt文件中提取10,000个数字,将它们传递到数组中,并将其作为我的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));

3 个答案:

答案 0 :(得分:1)

这是一个逻辑错误。您需要更改

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

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

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

答案 1 :(得分:0)

尝试一下:

const finalFile = file.split('\r?\n').map(.....)

答案 2 :(得分:0)

您的解析代码对我有用,除了一个问题:parseInt返回NaN作为最后一行,所以您需要像这样finalFile.pop();从数组中删除最后一个元素。但是,这不能解释为什么您会看到元素数量如此不同的原因。您发布的代码或文件中必须有其他内容。