1
- /*
1
+ /* *
2
2
*
3
3
* copyright The Algorithms
4
4
* Author -
5
5
* Correction - ayaankhan98
6
6
*
7
+ * Implementation Details -
8
+ * Quick Sort is a divide and conquer algorithm. It picks and element as
9
+ * pivot and partition the given array around the picked pivot. There
10
+ * are many different versions of quickSort that pick pivot in different
11
+ * ways.
12
+ *
13
+ * 1. Always pick the first element as pivot
14
+ * 2. Always pick the last element as pivot (implemented below)
15
+ * 3. Pick a random element as pivot
16
+ * 4. Pick median as pivot
17
+ *
18
+ * The key process in quickSort is partition(). Target of partition is,
19
+ * given an array and an element x(say) of array as pivot, put x at it's
20
+ * correct position in sorted array and put all smaller elements (samller
21
+ * than x) before x, and put all greater elements (greater than x) after
22
+ * x. All this should be done in linear time
23
+ *
7
24
*/
8
25
9
26
#include < cstdlib>
10
27
#include < iostream>
11
28
29
+ /* *
30
+ * This function takes last element as pivot, places
31
+ * the pivot element at its correct position in sorted
32
+ * array, and places all smaller (smaller than pivot)
33
+ * to left of pivot and all greater elements to right
34
+ * of pivot
35
+ *
36
+ */
37
+
12
38
int partition (int arr[], int low, int high) {
13
- int pivot = arr[high]; // pivot
39
+ int pivot = arr[high]; // taking the last element as pivot
14
40
int i = (low - 1 ); // Index of smaller element
15
41
16
42
for (int j = low; j < high; j++) {
@@ -29,6 +55,12 @@ int partition(int arr[], int low, int high) {
29
55
return (i + 1 );
30
56
}
31
57
58
+ /* *
59
+ * The main function that implements QuickSort
60
+ * arr[] --> Array to be sorted,
61
+ * low --> Starting index,
62
+ * high --> Ending index
63
+ */
32
64
void quickSort (int arr[], int low, int high) {
33
65
if (low < high) {
34
66
int p = partition (arr, low, high);
@@ -37,14 +69,14 @@ void quickSort(int arr[], int low, int high) {
37
69
}
38
70
}
39
71
72
+ // prints the array after sorting
40
73
void show (int arr[], int size) {
41
74
for (int i = 0 ; i < size; i++)
42
75
std::cout << arr[i] << " " ;
43
76
std::cout << " \n " ;
44
77
}
45
78
46
79
// Driver program to test above functions
47
-
48
80
int main () {
49
81
int size;
50
82
std::cout << " \n Enter the number of elements : " ;
0 commit comments