Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

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

Updated on: 2025-05-12T16:50:14+05:30

297 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements