-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path16.cpp
More file actions
77 lines (60 loc) · 1.53 KB
/
Copy path16.cpp
File metadata and controls
77 lines (60 loc) · 1.53 KB
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
// Quick Sort - Hoare's Partition
// https://www.geeksforgeeks.org/dsa/hoare-s-partition-algorithm/
#include <iostream>
using namespace std;
// Hoare's Partition function
int partition(int a[], int lb, int ub) {
int i, j, pivot;
pivot = a[lb]; // Choosing the first element as pivot
i = lb - 1;
j = ub + 1;
while (true) {
// Move i from left(to right) until an element >= pivot is found
do {
i++;
} while (a[i] < pivot);
// Move j from right(to left) until an element <= pivot is found
do {
j--;
} while (a[j] > pivot);
// If pointers cross, return partition index
if (i >= j)
return j;
// Swap elements
swap(a[i], a[j]);
}
}
// Quick Sort recursive function
void quicksort(int a[], int lb, int ub) {
int p;
if (lb < ub) {
p = partition(a, lb, ub);
quicksort(a, lb, p);
quicksort(a, p + 1, ub);
}
}
// Main function
int main() {
int a[20], n, i;
cout << "Enter the no. of elements: ";
cin >> n;
cout << "Enter elements:\n";
for (i = 0; i < n; i++) {
cout << "Element " << i + 1 << ": ";
cin >> a[i];
}
cout << "\nUnsorted Array:\n";
cout << "[";
for (i = 0; i < n; i++) {
cout << " " << a[i];
}
cout << " ]\n";
quicksort(a, 0, n - 1);
cout << "\nSorted Array:\n";
cout << "[";
for (i = 0; i < n; i++) {
cout << " " << a[i];
}
cout << " ]\n";
return 0;
}