2 Quick Sort
2 Quick Sort
Sargodha Campus
Advanced Algorithms
Assignment
Submitted to:
Submitted by:
Muhammad Arsalan
SU72-MSCSW-F24-004
Quick sort
Quick Sort works on the principle of divide and conquer, breaking down the problem into
smaller sub-problems.
There are mainly three steps in the algorithm:
1. Choose a Pivot: Select an element from the array as the pivot. The choice of pivot can
vary (e.g., first element, last element, random element, or median).
2. Partition the Array: Rearrange the array around the pivot. After partitioning, all elements
smaller than the pivot will be on its left, and all elements greater than the pivot will be on
its right. The pivot is then in its correct position, and we obtain the index of the pivot.
3. Recursively Call: Recursively apply the same process to the two partitioned sub-arrays
(left and right of the pivot).
4. Base Case: The recursion stops when there is only one element left in the sub-array, as a
single element is already sorted.
Choice of Pivot
int i = low - 1;
i++;
swap(arr[i], arr[j]);
return i + 1;
}
quickSort(arr, pi + 1, high);
int main() {
int n = arr.size();
quickSort(arr, 0, n - 1);
return 0;
Output:
Sorted Array
1 5 7 8 9 10
Time Complexity:
Best Case: (Ω (n log n)), Occurs when the pivot element divides the array into two equal
halves.
Average Case (θ (n log n)), on average, the pivot divides the array into two parts, but not
necessarily equal.
Worst Case: (O (n²)), Occurs when the smallest or largest element is always chosen as the
pivot (e.g., sorted arrays).
Auxiliary Space: O (n), due to recursive call stack
It works by selecting a ‘pivot’ element from the array and partitioning the other elements into
two sub-arrays, according to selecting a ‘pivot’ element from the array and partitioning the
other elements into two sub-arrays, according to whether they are less than or greater than the
pivot.