Search code examples
javascriptarraysscopemergesort

JS scope for merge sorting please help me understnad


can someone please to help me understand why the first block of code works but the second does not? Was trying to solve the problem of merging to arrays in order. First one is the solution code and second was the code I came up with. I can't get around why the i variable seems to stick around in the loops in the working one but in my code the arr1Item seems to disappear when trying to use it in the while loop?

const gerry = [0,3,4,31] 
const machmoud = [4,6,30]

const mergeSort = (arr1, arr2) => {
  const mergedArr = [];
  //init Counters
  let i= 1
  let j= 1
  let arr1Item = arr1[0]
  let arr2Item = arr2[0]
  
  while(arr1Item || arr2Item){        
    if(arr1Item < arr2Item || !arr2Item){
      mergedArr.push(arr1Item)
      arr1Item = arr1[i]
      i++
    }
      else{
        mergedArr.push(arr2Item)
        arr2Item = arr2[j]
        j++
      }
    
  }
  return mergedArr
}

console.log(mergeSort(gerry, machmoud))

2nd set of code

const gerry = [0,3,4,31] 
const machmoud = [4,6,30]

const mergeSort = (arr1, arr2) => {
  const mergedArr = [];
  //init Counters
  let i= 0
  let j= 0
  let arr1Item = arr1[j]
  let arr2Item = arr2[i]
  
  while(arr1Item || arr2Item){        
    if(arr1Item < arr2Item || !arr2Item){
      mergedArr.push(arr1Item)
      i++
    }
      else{
        mergedArr.push(arr2Item)
        j++
      }
    
  }
  return mergedArr
}


console.log(mergeSort(gerry, machmoud))

This runs into an infinite loop.


Solution

  • The main issue with your code (the second block) is that the loop never updates the value of arr1Item and arr2Item, and so the while condition can never evaluate to anything else than that it did the first time. Hence you get an infinite loop. So as soon as you change i or j should should also read the corresponding value from the array into the relevant variable.

    However, there is also a problem that both implementations suffer from. If they would get two arrays which both have 0 as their first array value, or even if only the second array would start with 0, the results would not be as expected. You should really compare with undefined. Here is your code corrected:

    const gerry = [0, 3, 4, 31];
    const machmoud = [4, 6, 30];
    
    const mergeSort = (arr1, arr2) => {
      const mergedArr = [];
      //init Counters
      let i = 0;
      let j = 0;
      let arr1Item = arr1[i];
      let arr2Item = arr2[j];
    
      while (arr1Item !== undefined || arr2Item !== undefined) {
        if (arr1Item < arr2Item || arr2Item === undefined) {
          mergedArr.push(arr1Item);
          i++;
          arr1Item = arr1[i];
        } else {
          mergedArr.push(arr2Item);
          j++;
          arr2Item = arr2[j];
        }
      }
      return mergedArr;
    }
    
    console.log(mergeSort(gerry, machmoud));