Home > OS >  mergeSort Algorithm giving the wrong output
mergeSort Algorithm giving the wrong output

Time:10-13

Can someone help me understand why this function is giving me this output?

function mergeSort(array) {
    if (array.length === 1) return array

    leftArraySorted = mergeSort(array.slice(0, (Math.floor(array.length / 2))))
    rightArraySorted = mergeSort(array.slice(Math.floor(array.length / 2)))

    let a = 0
    let b = 0
    const mergedSortedArray = []

    for (let i = 0; i < array.length; i  ) {
      if (leftArraySorted[a] < rightArraySorted[b]) {
        mergedSortedArray.push(leftArraySorted[a])
        a  = 1
      }

      else if (leftArraySorted[a] > rightArraySorted[b]) {
        mergedSortedArray.push(rightArraySorted[b])
        b  = 1
      }

      else if (leftArraySorted[a] === rightArraySorted[b]) {
        mergedSortedArray.push(leftArraySorted[a])
        a  = 1
      }

      else if (leftArraySorted[a] === undefined) {
        mergedSortedArray.push(rightArraySorted[b])
        b  = 1
      }

      else if (rightArraySorted[b] === undefined) {
        mergedSortedArray.push(leftArraySorted[a])
        a  = 1
      }
    }
    return mergedSortedArray
}

console.log(mergeSort(6, 3, 5) is outputting [3, 3 ,5], Why? Already went trough the code 50 times and can't figure out what is causing this.

CodePudding user response:

You should use the let keyword to declare those two local arrays

let leftArraySorted = mergeSort(array.slice(0, (Math.floor(array.length / 2))))
let rightArraySorted = mergeSort(array.slice(Math.floor(array.length / 2)))
  • Related