[Geeks for Geeks] Quick Sort

Quick Sort

Quick Sort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot.

Given an array arr[], its starting position low and its ending position high.

Implement the partition() and quickSort() functions to sort the array.

  • Time : O(nlogn) | worst O(n^2)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
//Function to sort an array using quick sort algorithm.
void quickSort(int arr[], int low, int high) {
if(low >= high) return;
int m = partition(arr, low, high);
quickSort(arr, low, m - 1);
quickSort(arr, m + 1, high);
}

public:
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int l = low, r = high - 1;
while(l <= r) {
while(l <= r and arr[l] <= pivot) l++;
while(l <= r and arr[r] >= pivot) r--;
if(l <= r and arr[l] >= arr[r]) swap(arr[l++],arr[r--]);
}
swap(arr[l], arr[high]);
return l;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/quick-sort/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.