generated from GauravWalia19/mernboilerplate
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathQuick_Sort.cpp
85 lines (74 loc) · 1.95 KB
/
Quick_Sort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* PROBLEM: Quick Sort in C++
* AUTHOR: sourishphate
**/
#include <iostream>
using namespace std;
/**
* This function swaps two elements in the array
*
* @param a: reference to the first element
* @param b: reference to the second element
**/
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
/**
* This function places the pivot element at its correct position
* and partitions the array into two halves
*
* @param A: the array to be partitioned
* @param low: starting index of the array
* @param high: ending index of the array
* @return: index of the pivot element
**/
int partition(int A[], int low , int high) {
int pivot = A[high]; // Choose the last element as the pivot
int i = low - 1; // Index of the smaller element
for (int j = low; j <= high - 1; j++) {
if (A[j] <= pivot) {
i++;
swap(A[i], A[j]);
}
}
swap(A[i + 1], A[high]); // Place pivot at the correct position
return (i + 1);
}
/**
* This function sorts an array using the quick sort algorithm
*
* @param A: the array to be sorted
* @param low: starting index of the array
* @param high: ending index of the array
**/
void quickSort(int A[], int low, int high) {
if (low < high) {
int p = partition(A, low, high); // Get the partition index
quickSort(A, low, p - 1); // Recursively sort the elements before and after partition
quickSort(A, p + 1, high);
}
}
/**
* This function prints the array
*
* @param A: the array to print
* @param size: size of the array
**/
void printArray(int A[], int size) {
for (int i = 0; i < size; i++) {
cout << A[i] << " ";
}
cout << endl;
}
int main() {
int A[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(A) / sizeof(A[0]);
cout << "Original array: ";
printArray(A, n);
quickSort(A, 0, n - 1);
cout << "Sorted array: ";
printArray(A, n);
return 0;
}