0

i am having hard time understanding the way the array is being passed and manipulated without having a return array in the partition function. the partition function only returns partitionIndex but the array is being changed anyway. can anyone explain

function QuickSort(arr,start,end,type){
console.log("_____________________________ "+type+" "+start+" "+end+" arr: "+arr);
if(start < end){
  var pivotIndex = Partition(arr,start,end);
  console.log("pivotIndex: ",pivotIndex);
  QuickSort(arr,start,pivotIndex-1,'inner1');
  QuickSort(arr,pivotIndex+1,end,'inner2');
}
return arr;
}

function Partition(arr,start,end){
  console.log("Partition");
  var pivot = arr[end];
  var partitionIndex = start;

  for(var x = start; x < end; x++ ){
    if(arr[x] <= pivot){
      swap(arr,x,partitionIndex)
      partitionIndex++;
    }
  }
 console.log("#####",arr)
 swap(arr,partitionIndex,end)
 console.log("@@@@@",arr)
 return partitionIndex;
}

function swap(arr,firstIndex,secondIndex){
 var temp = arr[firstIndex];
 arr[firstIndex] = arr[secondIndex];
 arr[secondIndex] = temp;
}

console.log(QuickSort(arr,start,end,'main'));
MaricelaO
  • 1
  • 1
  • 3
    Arrays in JS are "pass by reference", so if you pass the array to a function and it manipulates it, the original is also altered. – VLAZ May 19 '18 at 19:52
  • 1
    Right. To be more specific a copy of the reference is passed. – Attersson May 19 '18 at 19:54
  • See https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language – trincot May 19 '18 at 19:56

0 Answers0