partition (arr, low, high)
// pivot (Element to be placed at right position)
pivot = arr[high];
i = (low - 1) // Index of smaller element
for (j = low; j <= high- 1; j++) // no. of iterations=high-1-low+1
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
i++; // increment index of smaller element
swap arr[i] and arr[j]
swap arr[i + 1] and arr[high]) // +1 swap
return (i + 1)
To understand my doubt please refer to the code above.
In the 1st level high=n and low=1. For the worst case of swapping, for each iteration there should be swapping. Hence total no. of swappings would be high-1-low+1=n-1-1+0=n-2 and outside the loop there is another swapping. Total swapping would be = n-1 in the 1st level. No. of swaps=O(n).
At 2nd level, if the pivot divides the array into equal halves then no. of swapping in this way is (low=1,high=(n/2)-1) so total swaps= (n/2)-1-1+1+1=n/2 and as there is another array set where low=n/2+1 and high=n so swaps=n/2 and hence total swaps=n.
If pivot element is placed at the end (for sorted array) then, low=1, high=n-1 so swaps= high-1-low+1+1=(n-1)-1-1+1+1=n-1.
We can assume that at each level the no. of swaps is O(n).
No. of levels= logn.
Total no. of swaps = nlogn.
How will it be n^2 @Bikram Sir ?