Merge Sort doesn't accept correct answer

Tell us what’s happening:
Test claims I am using .sort() method even though I am not.
It also doesn’t accept the provided solution from here.

Your code so far


"use strict";
function mergeSort(array) {
// base case to end recursion
if (array.length <= 1) return array;

// locate middle to split array in half
var middle = Math.floor(array.length / 2);

// split array in two
const left = array.slice(0, middle);
const right = array.slice(middle);

// recursively merge left and right
return merge(mergeSort(left), mergeSort(right));
}

// helper function to merge two sorted arrays
function merge(left, right) {
// temp variables for keeping track of where we are and building sorted array
let result = [],
  leftIndex = 0,
  rightIndex = 0;

// add values to result in ascending order by iterating through all of left and right elements
while (leftIndex < left.length && rightIndex < right.length) {
  if (left[leftIndex] < right[rightIndex]) {
    result.push(left[leftIndex++]); // push element and then move left cursor along one
  } else {
    result.push(right[rightIndex++]); // push element and then move right cursor along one
  }
}

// concatenate as there will be at least one element remaining from left or right once the either index hits the end (can use ES6 spread operator syntax)

// return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex));
return [...result, ...left.slice(leftIndex), ...right.slice(rightIndex)];
}

console.log(mergeSort([2, 4, 7, 8, 4, 6, 1]));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36.

Challenge: Implement Merge Sort

Link to the challenge:

Hello there.

The tests are looking for the word sort. You are using this word in your comments:

// helper function to merge two sorted arrays
function merge(left, right) {
// temp variables for keeping track of where we are and building sorted array

Remove these two lines of comments to pass.

Hope this helps

1 Like

This works, thank you!