I am learning the Quicksort algorithm and I am struggling with understanding the time complexity.
Here is the JavaScript ES6 code for the partition function that is used in the algorithm:
let partition = function(arr, low, high) { let pivotValue = arr[low]; let i = low; let j = high; while (i < j) { while (i <= high && arr[i] <= pivotValue) { i++; } while (arr[j] > pivotValue) { j--; } if (i < j) { // swap arr[i], arr[j] let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } arr[low] = arr[j]; arr[j] = pivotValue; return j; }; I read that there is n work done for a single invocation of the partition function because there is n - 1 work being done in the while loop and 1 unit of work being done when copying the pivot back.
I don't understand why there is n - 1 work done in the while loop. As per my understanding, every time you make a comparison between the array value and pivotValue (arr[i] <= pivotValue or arr[j] > pivotValue), that is a unit of work being done.
So aren't there actually n units of work being done in the while loop, for a total of n + 1 in the partition function?