Skip to content

Commit 76c752b

Browse files
committed
Added 3-way quick sort
1 parent 566759f commit 76c752b

File tree

2 files changed

+64
-1
lines changed

2 files changed

+64
-1
lines changed
+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
void swap(int &a, int &b)
6+
{
7+
int t = a;
8+
a = b;
9+
b = t;
10+
}
11+
12+
void partition(int a[], int low, int high, int &i, int &j)
13+
{
14+
// To handle two elemts
15+
if (high - low <= 1)
16+
{
17+
if (a[high] < a[low])
18+
swap(a[high], a[low]);
19+
i = low;
20+
j = high;
21+
return;
22+
}
23+
24+
int mid = low;
25+
int pivot = a[high];
26+
27+
while (mid <= high)
28+
{
29+
if (a[mid] < pivot)
30+
swap(a[low++], a[mid++]);
31+
else if (a[mid] == pivot)
32+
mid++;
33+
else if (a[mid] > pivot)
34+
swap(a[mid], a[high--]);
35+
}
36+
37+
i = low - 1;
38+
j = mid;
39+
}
40+
41+
void quickSort(int a[], int low, int high)
42+
{
43+
if (low >= high)
44+
return;
45+
int i, j;
46+
47+
partition(a, low, high, i, j);
48+
quickSort(a, low, i);
49+
quickSort(a, j, high);
50+
}
51+
52+
int main()
53+
{
54+
int arr[] = {64, 25, 25, 11, 11, 12, 22, 11};
55+
int n = sizeof(arr)/sizeof(arr[0]);
56+
quickSort(arr, 0, n - 1);
57+
cout << "Sorted array: \n";
58+
for (int i = 0; i < n; i++)
59+
{
60+
cout << arr[i] << " ";
61+
}
62+
return 0;
63+
}

Algorithms/Sorting/selection_sort.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,4 @@ int main()
3333
cout << arr[i] << " ";
3434
}
3535
return 0;
36-
}
36+
}

0 commit comments

Comments
 (0)