1- /*
1+ /* *
22 *
33 * copyright The Algorithms
44 * Author -
55 * Correction - ayaankhan98
66 *
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+ *
724 */
825
926#include < cstdlib>
1027#include < iostream>
1128
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+
1238int partition (int arr[], int low, int high) {
13- int pivot = arr[high]; // pivot
39+ int pivot = arr[high]; // taking the last element as pivot
1440 int i = (low - 1 ); // Index of smaller element
1541
1642 for (int j = low; j < high; j++) {
@@ -29,6 +55,12 @@ int partition(int arr[], int low, int high) {
2955 return (i + 1 );
3056}
3157
58+ /* *
59+ * The main function that implements QuickSort
60+ * arr[] --> Array to be sorted,
61+ * low --> Starting index,
62+ * high --> Ending index
63+ */
3264void quickSort (int arr[], int low, int high) {
3365 if (low < high) {
3466 int p = partition (arr, low, high);
@@ -37,14 +69,14 @@ void quickSort(int arr[], int low, int high) {
3769 }
3870}
3971
72+ // prints the array after sorting
4073void show (int arr[], int size) {
4174 for (int i = 0 ; i < size; i++)
4275 std::cout << arr[i] << " " ;
4376 std::cout << " \n " ;
4477}
4578
4679// Driver program to test above functions
47-
4880int main () {
4981 int size;
5082 std::cout << " \n Enter the number of elements : " ;
0 commit comments