-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquick_sort.cpp
executable file
·74 lines (65 loc) · 1.59 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <bits/stdc++.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void swapBitwise(int *a, int *b)
{
*a = *a ^ *b;
*b = *b ^ *a;
*a = *a ^ *b;
}
/*
This Function is for dividing the array into two subarray where
the left side of pivot is lower than pivot and the right side is greater than pivot
*/
int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int pindex = 0;
int i = 0;
while (i < high)
{
if (arr[i] < pivot)
{
// Swaping index with pindex if the value of arr[i] < pivot
swap(&arr[pindex], &arr[i]);
pindex++;
}
i++;
}
swap(&arr[high], &arr[pindex]);
std::cout << pindex << std::endl;
return pindex;
}
void quickSort(int arr[], int low, int high)
{
// This is the base condition of exiting this QuickSort Function
if (low >= high)
{
return;
}
// in this variable we are storing the index where out pivot is after partitioning
int partionIndex = partition(arr, low, high);
quickSort(arr, low, partionIndex - 1);
quickSort(arr, partionIndex + 1, high);
}
// This is an Utility function to print a Array
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
int main()
{
int arr[6] = {30, 25, 40, 50, 10, 5};
int size = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, size - 1);
printArray(arr, size);
return 0;
}