-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuick_Sort.cpp
57 lines (49 loc) · 1.07 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
#include<iostream>
using namespace std;
void swapElements(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
int partition(int* arr, int startingIndex, int endingIndex)
{
int pIndex{0};
int pivot = arr[endingIndex];
for(int i = 0; i < endingIndex; ++i)
{
if(arr[i] < pivot)
{
swapElements(arr[i], arr[pIndex]);
++pIndex;
}
}
swapElements(arr[pIndex], arr[endingIndex]);
return pIndex;
}
void quickSort(int* arr, int lowerIndex, int higherIndex)
{
if(lowerIndex < higherIndex)
{
int p = partition(arr, lowerIndex, higherIndex);
quickSort(arr, lowerIndex, p-1);
quickSort(arr, p+1, higherIndex);
}
}
int main()
{
int arr[7]{2,3,6,5,7,1,4};
cout << "Before Sorting:\n";
for(int element : arr)
{
cout << element << " ";
}
quickSort(arr, 0, 6);
cout << "\nAfter Sorting\n";
for(int element : arr)
{
cout << element << " ";
}
cout << "\n";
return 0;
}