-
Notifications
You must be signed in to change notification settings - Fork 0
/
QuickSort.cpp
56 lines (52 loc) · 1021 Bytes
/
QuickSort.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
#include <iostream>
using namespace std;
void swap(int& a, int& b)
{
int tmp = a;
a = b;
b = tmp;
}
int partition(int* a, int l, int r)
{
int pivot = a[r];
int index = l - 1;
for (int j = l; j < r; j++)
{
if (a[j] <= pivot)
{
index++;
swap(a[index], a[j]);
}
}
swap(a[index + 1], a[r]);
return index + 1;
}
void quickSort(int* a, int l, int r)
{
if (l < r)
{
int mid = partition(a, l, r);
quickSort(a, l, mid - 1);
quickSort(a, mid + 1, r);
}
}
int main()
{
int size = 0;
cout << "Enter array size: ";
cin >> size;
cout << "Enter array elements: ";
int* a = new int[size];
for (int i = 0; i < size; i++)
{
cin >> a[i];
}
quickSort(a, 0, size - 1);
cout << "Array after sorting: ";
for (int i = 0; i < size; i++)
{
cout << a[i] << " ";
}
delete[] a;
return 0;
}