C++ Program for Stooge Sort
Last Updated :
13 Jun, 2022
The Stooge sort is a recursive sorting algorithm. It is defined as below (for ascending order sorting).
Step 1 : If value at index 0 is greater than
value at last index, swap them.
Step 2: Recursively,
a) Stooge sort the initial 2/3rd of the array.
b) Stooge sort the last 2/3rd of the array.
c) Stooge sort the initial 2/3rd again to confirm.
CPP
#include <iostream>
using namespace std;
void stoogesort( int arr[], int l, int h)
{
if (l >= h)
return ;
if (arr[l] > arr[h])
swap(arr[l], arr[h]);
if (h-l+1>2)
{
int t = (h-l+1)/3;
stoogesort(arr, l, h-t);
stoogesort(arr, l+t, h);
stoogesort(arr, l, h-t);
}
}
int main()
{
int arr[] = {2, 4, 5, 3, 1};
int n = sizeof (arr)/ sizeof (arr[0]);
stoogesort(arr, 0, n-1);
for ( int i=0; i<n; i++)
cout << arr[i] << " " ;
return 0;
}
|
Output:
1 2 3 4 5
Time Complexity:
The running time complexity of stooge sort can be written as,
T(n) = 3T(3n/2) + O(1)
Solution of above recurrence is O(n(log3/log1.5)) = O(n2.709), hence it is slower than even bubble sort(n2).
Auxiliary Space: O(n)
Please refer complete article on Stooge Sort for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...