-
Notifications
You must be signed in to change notification settings - Fork 83
/
Quick_sort_algorithm.cpp
71 lines (66 loc) · 1.3 KB
/
Quick_sort_algorithm.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
#include <iostream>
using namespace std;
class quicksort {
int a[50];
public:
void getdata(int n)
{
cout << "Enter array elements :- ";
for (int i = 0; i < n; i++) {
cin >> a[i];
}
}
void display(int n)
{
cout << "Sorted array : " << endl;
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
}
void swap(int& a, int& b)
{
int temp;
temp = a;
a = b;
b = temp;
}
int partition(int low, int high)
{
int pivot;
pivot = a[low];
int i = low + 1;
int j = high;
do {
while (a[i] < pivot) {
i++;
}
while (a[j] > pivot) {
j--;
}
if (i < j) {
swap(a[i], a[j]);
}
} while (i <= j);
swap(a[low], a[j]);
return j;
}
void quick_sort(int low, int high)
{
int j;
if (low < high) {
j = partition(low, high);
quick_sort(low, j - 1);
quick_sort(j + 1, high);
}
}
};
int main()
{
quicksort q;
int n;
cout << "Enter total number of elements : ";
cin >> n;
q.getdata(n);
q.quick_sort(0, n - 1);
q.display(n);
}