Stooge sort (sorting by parts) – a recursive array sorting algorithm.
Description of the sorting algorithm by parts
The stooge sort sorting algorithm is as follows:
- If the value of the last element of the array is less than the value of the first element, then we swap them;
- If the array contains three or more elements, then:
- Recursively call the method for the first 2⁄3 elements;
- Recursively call the method for the last 2⁄3 elements;
- Again, recursively call the method for the first 2⁄3 elements;
Implementation of Stooge sort
using System;
class program
{
// element exchange method
static void Swap(ref int a, ref int b)
{
var t = a;
a = b;
b = t;
}
// sort by parts
static int[] StoogeSort(int[] array, int startIndex, int endIndex)
{
if (array[startIndex] > array[endIndex])
{
Swap(ref array[startIndex], ref array[endIndex]);
}
if (endIndex - startIndex > 1)
{
var len = (endIndex - startIndex + 1) / 3;
StoogeSort(array, startIndex, endIndex - len);
StoogeSort(array, startIndex + len, endIndex);
StoogeSort(array, startIndex, endIndex - len);
}
return array;
}
static int[] StoogeSort(int[] array)
{
return StoogeSort(array, 0, array.Length - 1);
}
static void Main(string[] args)
{
Console.WriteLine("Sort in parts");
Console.Write("Enter elements of the array:");
var parts = Console.ReadLine().Split(new[] { "", ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
var array = new int[parts.Length];
for (int i = 0; i < parts.Length; i++)
{
array[i] = Convert.ToInt32(parts[i]);
}
Console.WriteLine("Ordered array: {0}", string.Join(",", StoogeSort(array)));
Console.ReadLine();
}
}
The result of the program: