forked from kothariji/competitive-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStoogeSort.cpp
51 lines (40 loc) · 1.08 KB
/
StoogeSort.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
// C++ code to implement stooge sort
#include <iostream>
using namespace std;
// Function to implement stooge sort
void stoogesort(int arr[], int l, int h)
{
if (l >= h)
return;
// If first element is smaller than last,
// swap them
if (arr[l] > arr[h])
swap(arr[l], arr[h]);
// If there are more than 2 elements in
// the array
if (h - l + 1 > 2) {
int t = (h - l + 1) / 3;
// Recursively sort first 2/3 elements
stoogesort(arr, l, h - t);
// Recursively sort last 2/3 elements
stoogesort(arr, l + t, h);
// Recursively sort first 2/3 elements
// again to confirm
stoogesort(arr, l, h - t);
}
}
// Driver Code
int main()
{
int arr[] = { 2, 4, 5, 3, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
// Calling Stooge Sort function to sort
// the array
stoogesort(arr, 0, n - 1);
// Display the sorted array
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Output:
1 2 3 4 5