-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path46_Quick_sort.cpp
70 lines (61 loc) · 1.39 KB
/
46_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
#include <bits/stdc++.h>
using namespace std;
void printArray(int *arr, int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
}
int partition(int *arr, int low, int high)
{
int pivot = arr[low];
int i = low + 1;
int j = high;
int temp;
do
{
while (arr[i] <= pivot)
{
i++;
}
while (arr[j] > pivot)
{
j--;
}
if (i < j)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
} while (i < j);
// Swap arr[low] and arr[j]
temp = arr[low];
arr[low] = arr[j];
arr[j] = temp;
return j;
}
void quickSort(int *arr, int low, int high)
{
int partitionIndex; // index of pivot after partition
if (low < high)
{
partitionIndex = partition(arr, low, high);
quickSort(arr, low, partitionIndex - 1); // sort left subarray
quickSort(arr, partitionIndex + 1, high); // sort right subarray
}
}
int main()
{
int arr[] = {12, 74, 89, 3, 14, 25, 47, 99};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "The given array is: ";
printArray(arr, size);
int low = 0;
int high = size - 1;
quickSort(arr, low, high);
cout << "\nThe sorted array is: ";
printArray(arr, size);
return 0;
}