Thursday, October 9, 2025
HomeData Modelling & AIJava Program for Stooge Sort

Java Program for Stooge Sort

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.

Java




// Java program to implement stooge sort
import java.io.*;
 
public class stooge
{
 // Function to implement stooge sort
 static 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])
  {
   int t = arr[l];
   arr[l] = arr[h];
   arr[h] = t;
  }
 
  // 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
 public static void main(String args[])
 {
  int arr[] = {2, 4, 5, 3, 1};
  int n = arr.length;
 
  stoogesort(arr, 0, n-1);
 
  for (int i=0; i < n; i++)
   System.out.print(arr[i] + " ");
 }
}
// Code Contributed by Mohit Gupta_OMG <(0_o)>


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!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32346 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6715 POSTS0 COMMENTS
Nicole Veronica
11878 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6837 POSTS0 COMMENTS
Ted Musemwa
7095 POSTS0 COMMENTS
Thapelo Manthata
6790 POSTS0 COMMENTS
Umr Jansen
6791 POSTS0 COMMENTS