Sorting algorithms/Stooge sort

From Rosetta Code
Revision as of 05:00, 24 July 2010 by rosettacode>Mwn3d (Created task with Java)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Sorting algorithms/Stooge sort
You are encouraged to solve this task according to the task description, using any language you may know.
This page uses content from Wikipedia. The original article was at Sorting algorithms/Stooge sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)

Show the Stooge Sort for an array of integers. The Stooge Sort algorithm is as follows:

algorithm stoogesort(array L, i = 0, j = length(L)-1)
     if L[j] < L[i] then
         L[i] ↔ L[j]
     if j - i > 1 then
         t = (j - i + 1)/3
         stoogesort(L, i  , j-t)
         stoogesort(L, i+t, j  )
         stoogesort(L, i  , j-t)
     return L

Java

<lang java>import java.util.Arrays;

public class Stooge {

   public static void main(String[] args) {
       int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};
       stoogeSort(nums);
       System.out.println(Arrays.toString(nums));
   }
   public static void stoogeSort(int[] L) {
       stoogeSort(L, 0, L.length - 1);
   }
   public static void stoogeSort(int[] L, int i, int j) {
       if (L[j] < L[i]) {
           int tmp = L[i];
           L[i] = L[j];
           L[j] = tmp;
       }
       if (j - i > 1) {
           int t = (j - i + 1) / 3;
           stoogeSort(L, i, j - t);
           stoogeSort(L, i + t, j);
           stoogeSort(L, i, j - t);
       }
   }

}</lang> Output:

[-6, -5, -2, 1, 3, 3, 4, 5, 7, 10]