Skip to content

Commit 852cd95

Browse files
committed
add quick sort
1 parent bf566b3 commit 852cd95

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

C++/quicksort.cpp

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// C++ Implementation of the Quick Sort Algorithm.
2+
#include <iostream>
3+
using namespace std;
4+
5+
int partition(int arr[], int start, int end)
6+
{
7+
8+
int pivot = arr[start];
9+
10+
int count = 0;
11+
for (int i = start + 1; i <= end; i++) {
12+
if (arr[i] <= pivot)
13+
count++;
14+
}
15+
16+
// Giving pivot element its correct position
17+
int pivotIndex = start + count;
18+
swap(arr[pivotIndex], arr[start]);
19+
20+
// Sorting left and right parts of the pivot element
21+
int i = start, j = end;
22+
23+
while (i < pivotIndex && j > pivotIndex) {
24+
25+
while (arr[i] <= pivot) {
26+
i++;
27+
}
28+
29+
while (arr[j] > pivot) {
30+
j--;
31+
}
32+
33+
if (i < pivotIndex && j > pivotIndex) {
34+
swap(arr[i++], arr[j--]);
35+
}
36+
}
37+
38+
return pivotIndex;
39+
}
40+
41+
void quickSort(int arr[], int start, int end)
42+
{
43+
44+
// base case
45+
if (start >= end)
46+
return;
47+
48+
// partitioning the array
49+
int p = partition(arr, start, end);
50+
51+
// Sorting the left part
52+
quickSort(arr, start, p - 1);
53+
54+
// Sorting the right part
55+
quickSort(arr, p + 1, end);
56+
}
57+
58+
int main()
59+
{
60+
61+
int arr[] = { 9, 3, 4, 2, 1, 8 };
62+
int n = 6;
63+
64+
quickSort(arr, 0, n - 1);
65+
66+
for (int i = 0; i < n; i++) {
67+
cout << arr[i] << " ";
68+
}
69+
70+
return 0;
71+
}

0 commit comments

Comments
 (0)