Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Perform Stooge Sort
Stooge Sort is a recursive sorting algorithm used to sort the given data. The stooge sort divides the array into two overlapping parts, 2/3 each and then sort the array in three steps by sorting first then second and again first part. The worst case time complexity of this algorithm is O(n^2.7095).
In this article, we have an unsorted array. Our task is to implement the stooge sort algorithm for sorting the given array in C++.
Example
Here is an example of sorting the given array using stooge sort:
Input:
array = {5, 3, 8, 4, 2, 7}
Output:
Sorted array = {2, 3, 4, 5, 7, 8}
Steps to Implement Stooge Sort in C++
The steps to implement the stooge sort is given below.
- First, we check the first and the last element of the array. If the first element is > the last element of the array, we swap them.
- Then, using the if condition, we define the base condition for the recursive function stoogeSort(), i.e., the array must contain more than 2 elements.
- Then we recursively call the stoogeSort() on the first 2/3rd part of the array, then the last 2/3rd part, and then the first 2/3rd part of the array again.
- The above step sorts the array recursively, and we display the sorted array in the main() function.
C++ Implementation of Stooge Sort
Here is the code implementation of stooge sort to sort the given array in C++.
#include<iostream>
using namespace std;
void stoogeSort(int a[], int start, int end) {
if(a[end] < a[start]) {
int temp = a[start];
a[start] = a[end];
a[end] = temp;
}
if(end - start + 1 > 2) {
int pivot = (end - start + 1) / 3;
stoogeSort(a, start, end - pivot);
stoogeSort(a, start + pivot, end);
stoogeSort(a, start, end - pivot);
}
}
int main() {
int arr[] = {5, 3, 8, 4, 2, 7};
int m = sizeof(arr)/sizeof(arr[0]);
int i;
cout << "Array before sorting: ";
for (i = 0; i < m; i++) {
cout << arr[i] << " " ;
}
stoogeSort(arr, 0, m - 1);
cout << "\nSorted array: ";
for (i = 0; i < m; i++) {
cout << arr[i] << " " ;
}
return 0;
}
The output of the above code is as follows:
Array before sorting: 5 3 8 4 2 7 Sorted array: 2 3 4 5 7 8
Complexity of Stooge Sort Algorithm
- Time Complexity: The time complexity of the stooge sort algorithm is O(n^2.7095).
- Space Complexity: The space complexity of the stooge sort algorithm is O(logn).
Advertisements