The Slowest Sorting Algorithms
Last Updated :
02 Nov, 2023
A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of the element in the respective data structure. But Below is some of the slowest sorting algorithms:
Stooge Sort: A Stooge sort is a recursive sorting algorithm. It recursively divides and sorts the array in parts.
Below are the steps of the Stooge Sort:
- If the value at index 0 is greater than the value at the last index, swap them.
- If the number of elements in the array is greater than two:
- Recursively call stoogesort function for the initial 2/3rd elements of the array.
- Recursively call stoogesort function for the last 2/3rd elements of the array.
- Recursively call stoogesort function for the initial 2/3rd elements again to confirm the resultant array is sorted or not.
- Print the sorted array.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void stoogesort( int arr[], int l, int h)
{
if (l >= h)
return ;
if (arr[l] > arr[h])
swap(arr[l], arr[h]);
if (h - l + 1 > 2) {
int t = (h - l + 1) / 3;
stoogesort(arr, l, h - t);
stoogesort(arr, l + t, h);
stoogesort(arr, l, h - t);
}
}
int main()
{
int arr[] = { 2, 4, 5, 3, 1 };
int N = sizeof (arr) / sizeof (arr[0]);
stoogesort(arr, 0, N - 1);
for ( int i = 0; i < N; i++) {
cout << arr[i] << " " ;
}
return 0;
}
|
Java
class GFG{
static void stoogesort( int arr[],
int l, int h)
{
if (l >= h)
return ;
if (arr[l] > arr[h])
{
int temp = arr[l];
arr[l] = arr[h];
arr[h] = temp;
}
if (h - l + 1 > 2 )
{
int t = (h - l + 1 ) / 3 ;
stoogesort(arr, l, h - t);
stoogesort(arr, l + t, h);
stoogesort(arr, l, h - t);
}
}
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] + " " );
}
}
}
|
Python3
def stoogesort(arr, l, h):
if (l > = h):
return
if (arr[l] > arr[h]):
temp = arr[l]
arr[l] = arr[h]
arr[h] = temp
if (h - l + 1 > 2 ):
t = (h - l + 1 ) / / 3
stoogesort(arr, l, h - t)
stoogesort(arr, l + t, h)
stoogesort(arr, l, h - t)
arr = [ 2 , 4 , 5 , 3 , 1 ]
N = len (arr)
stoogesort(arr, 0 , N - 1 )
for i in range (N):
print (arr[i], end = " " )
|
C#
using System;
class GFG{
static void stoogesort( int []arr,
int l, int h)
{
if (l >= h)
return ;
if (arr[l] > arr[h])
{
int temp = arr[l];
arr[l] = arr[h];
arr[h] = temp;
}
if (h - l + 1 > 2)
{
int t = (h - l + 1) / 3;
stoogesort(arr, l, h - t);
stoogesort(arr, l + t, h);
stoogesort(arr, l, h - t);
}
}
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++)
{
Console.Write(arr[i] + " " );
}
}
}
|
Javascript
<script>
function stoogesort(arr, l, h)
{
if (l >= h)
return ;
if (arr[l] > arr[h])
{
let temp = arr[l];
arr[l] = arr[h];
arr[h] = temp;
}
if (h - l + 1 > 2)
{
let t = Math.floor((h - l + 1) / 3);
stoogesort(arr, l, h - t);
stoogesort(arr, l + t, h);
stoogesort(arr, l, h - t);
}
}
let arr = [ 2, 4, 5, 3, 1 ];
let N = arr.length;
stoogesort(arr, 0, N - 1);
for (let i = 0; i < N; i++)
{
document.write(arr[i] + " " );
}
</script>
|
Time Complexity: O(N2.709). Therefore, it is slower than even the Bubble Sort that has a time complexity of O(N2).
Slow Sort: The slow sort is an example of Multiply And Surrender a tongue-in-cheek joke of divide and conquer. Slow sort stores the maximum element of the array at the last position by recursively divides the array by half and compares each of them. Then it recursively calls the array without the previous maximum element and stores the new maximum element at the new last position.
Below are the steps of Slow sort:
- Find the maximum of the array and place it at the end of the array by
- Recursively call slowsort function for the maximum of the first N/2 elements.
- Recursively call slowsort function for the maximum of the remaining N/2 elements.
- Find the largest of that two maximum and store it at the end.
- Recursively call slowsort function for the entire array except for the maximum.
- Print the sorted array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void swap( int * xp, int * yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void slowSort( int A[], int i, int j)
{
if (i >= j)
return ;
int m = (i + j) / 2;
slowSort(A, i, m);
slowSort(A, m + 1, j);
if (A[j] < A[m]) {
swap(&A[j], &A[m]);
}
slowSort(A, i, j - 1);
}
void printArray( int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " " ;
cout << endl;
}
int main()
{
int arr[] = { 6, 8, 9, 4, 12, 1 };
int N = sizeof (arr) / sizeof (arr[0]);
slowSort(arr, 0, N - 1);
printArray(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void slowSort( int A[], int i, int j)
{
if (i >= j)
return ;
int m = (i + j) / 2 ;
slowSort(A, i, m);
slowSort(A, m + 1 , j);
if (A[j] < A[m])
{
int temp = A[j];
A[j] = A[m];
A[m] = temp;
}
slowSort(A, i, j - 1 );
}
static void printArray( int arr[], int size)
{
int i;
for (i = 0 ; i < size; i++)
System.out.print(arr[i]+ " " );
System.out.println();
}
public static void main(String[] args)
{
int arr[] = { 6 , 8 , 9 , 4 , 12 , 1 };
int N = arr.length;
slowSort(arr, 0 , N - 1 );
printArray(arr, N);
}
}
|
Python3
def slowSort(A, i, j):
if (i > = j):
return ;
m = (i + j) / / 2 ;
slowSort(A, i, m);
slowSort(A, m + 1 , j);
if (A[j] < A[m]):
temp = A[j];
A[j] = A[m];
A[m] = temp;
slowSort(A, i, j - 1 );
def printArray(arr, size):
i = 0 ;
for i in range (size):
print (arr[i], end = " " );
print ();
if __name__ = = '__main__' :
arr = [ 6 , 8 , 9 , 4 , 12 , 1 ];
N = len (arr);
slowSort(arr, 0 , N - 1 );
printArray(arr, N);
|
C#
using System;
class GFG
{
static void slowSort( int []A, int i, int j)
{
if (i >= j)
return ;
int m = (i + j) / 2;
slowSort(A, i, m);
slowSort(A, m + 1, j);
if (A[j] < A[m])
{
int temp = A[j];
A[j] = A[m];
A[m] = temp;
}
slowSort(A, i, j - 1);
}
static void printArray( int []arr, int size)
{
int i;
for (i = 0; i < size; i++)
Console.Write(arr[i] + " " );
Console.WriteLine();
}
public static void Main(String[] args)
{
int []arr = { 6, 8, 9, 4, 12, 1 };
int N = arr.Length;
slowSort(arr, 0, N - 1);
printArray(arr, N);
}
}
|
Javascript
<script>
function slowSort(A, i,j)
{
if (i >= j)
return ;
var m = parseInt((i + j) / 2);
slowSort(A, i, m);
slowSort(A, m + 1, j);
if (A[j] < A[m]) {
var t = A[j];
A[j]=A[m];
A[m]=t;
}
slowSort(A, i, j - 1);
}
function printArray(arr, size)
{
var i;
for (i = 0; i < size; i++)
document.write( arr[i] + " " );
document.write( "<br>" );
}
var arr = [ 6, 8, 9, 4, 12, 1 ];
var N = arr.length;
slowSort(arr, 0, N - 1);
printArray(arr, N);
</script>
|
Time Complexity:
- Base Case: O(N((log N)/(2+e)) where, e > 0
- Average Case: O(N(log(N)/2))
Even the best case is worse than Bubble sort. It is less efficient than Stooge sort.
Sleep Sort: Below are the steps of Sleep sort:
- Create different threads for each of the elements in the input array and then each thread sleeps for an amount of time which is proportional to the value of the corresponding array element.
- The thread having the least amount of sleeping time wakes up first and the number gets printed and then the second least element and so on.
- The largest element wakes up after a long time and then the element gets printed at the last. Thus, the output is a sorted one.
All this Multithreading process happens in the background and at the core of the OS
Below is the implementation of the above approach:
C++
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
vector< int > A;
void printArray(vector< int > arr, int size)
{
int i;
for (i = 0; i < size; i++) {
cout << arr[i] << " " ;
}
}
void add( int x)
{
sleep(x);
A.push_back(x);
}
void sleepSort( int arr[], int N)
{
vector< thread > threads;
for ( int i = 0; i < N; i++) {
threads.push_back(
thread (add, arr[i]));
}
for ( auto & th : threads) {
th.join();
}
cout << "Array after sorting: " ;
printArray(A, A.size());
}
int main()
{
int arr[] = { 8, 9, 1, 4, 3 };
int N = sizeof (arr) / sizeof (arr[0]);
sleepSort(arr, N);
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Main {
private static List<Integer> A = Collections.synchronizedList( new ArrayList<Integer>());
private static void printList(List<Integer> list) {
for ( int i : list) {
System.out.print(i + " " );
}
}
private static class Add implements Runnable {
private int x;
Add( int x) {
this .x = x;
}
@Override
public void run() {
try {
Thread.sleep(x * 1000 );
} catch (InterruptedException e) {
e.printStackTrace();
}
A.add(x);
}
}
private static void sleepSort(List<Integer> list) {
List<Thread> threads = new ArrayList<Thread>();
for ( int i : list) {
threads.add( new Thread( new Add(i)));
}
for (Thread th : threads) {
th.start();
}
for (Thread th : threads) {
try {
th.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print( "List after sorting: " );
Collections.sort(A);
printList(A);
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add( 8 );
list.add( 9 );
list.add( 1 );
list.add( 4 );
list.add( 3 );
sleepSort(list);
}
}
|
Python3
import threading
import time
A = []
def printArray(arr):
for i in arr:
print (i, end = ' ' )
def add(x):
time.sleep(x)
A.append(x)
def sleepSort(arr):
threads = []
for i in arr:
threads.append(threading.Thread(target = add, args = (i,)))
for th in threads:
th.start()
for th in threads:
th.join()
print ( "Array after sorting: " , end = '')
printArray( sorted (A))
if __name__ = = '__main__' :
arr = [ 8 , 9 , 1 , 4 , 3 ]
sleepSort(arr)
|
C#
using System;
using System.Collections.Generic;
using System.Threading;
class Program {
static List< int > A = new List< int >();
static void PrintArray(List< int > arr, int size)
{
for ( int i = 0; i < size; i++) {
Console.Write(arr[i] + " " );
}
}
static void Add( int x)
{
Thread.Sleep(x);
lock (A) { A.Add(x); }
}
static void SleepSort( int [] arr, int N)
{
List<Thread> threads = new List<Thread>();
for ( int i = 0; i < N; i++) {
threads.Add( new Thread(() = > Add(arr[i])));
threads[i].Start();
}
foreach ( var thread in threads) { thread.Join(); }
Console.Write( "Array after sorting: " );
PrintArray(A, A.Count);
}
static void Main()
{
int [] arr = { 8, 9, 1, 4, 3 };
int N = arr.Length;
SleepSort(arr, N);
}
}
|
Javascript
let A = [];
function printArray(arr) {
console.log(arr.join( ' ' ))
}
function add(x) {
setTimeout(() => {
A.push(x);
}, x);
}
function sleepSort(arr) {
let threads = [];
for (let i of arr) {
add(i);
}
setTimeout(() => {
process.stdout.write( "Array after sorting: " );
printArray(A.sort());
}, Math.max(...arr));
}
let arr = [8, 9, 1, 4, 3];
sleepSort(arr);
|
Output
Array after sorting 1 3 4 8 9
Time Complexity: O(max(input) + N) where, input = value of array element
Other algorithm’s time complexity depends upon the number of data but for sleep sort, it depends on the amount of data. This algorithm won’t work for negative numbers as a thread cannot sleep for a negative amount of time.
Bogo Sort: Two versions of this algorithm exist: one enumerates all permutations until it hits a sorted one, and a randomized version that randomly permutes its input.
Example 1:
C++
#include <bits/stdc++.h>
using namespace std;
void bogosort( int arr[], int N)
{
while (!is_sorted(arr, arr + N)) {
next_permutation(arr, arr + N);
}
}
int main()
{
int arr[] = { 8, 9, 1, 4, 3 };
int N = sizeof (arr) / sizeof (arr[0]);
bogosort(arr, N);
cout << "Array after sorting " ;
for ( int i = 0; i < N; ++i) {
cout << arr[i] << " " ;
}
cout << endl;
return 0;
}
|
Java
import java.util.*;
public class BogoSort {
public static void bogosort( int [] arr) {
Random rand = new Random();
while (!isSorted(arr)) {
for ( int i = 0 ; i < arr.length; i++) {
int randomIndex = rand.nextInt(arr.length);
int temp = arr[i];
arr[i] = arr[randomIndex];
arr[randomIndex] = temp;
}
}
}
public static boolean isSorted( int [] arr) {
for ( int i = 0 ; i < arr.length - 1 ; i++) {
if (arr[i] > arr[i + 1 ]) {
return false ;
}
}
return true ;
}
public static void main(String[] args) {
int [] arr = { 8 , 9 , 1 , 4 , 3 };
bogosort(arr);
System.out.println( "Array after sorting: " + Arrays.toString(arr));
}
}
|
Python3
import random
def bogosort(arr):
while not all (arr[i] < = arr[i + 1 ] for i in range ( len (arr) - 1 )):
random.shuffle(arr)
if __name__ = = "__main__" :
arr = [ 8 , 9 , 1 , 4 , 3 ]
bogosort(arr)
print ( "Array after sorting" , arr)
|
C#
using System;
class Program {
static void Main( string [] args)
{
int [] arr = { 8, 9, 1, 4, 3 };
int N = arr.Length;
bogosort(arr, N);
Console.Write( "Array after sorting: " );
for ( int i = 0; i < N; ++i) {
Console.Write(arr[i] + " " );
}
Console.WriteLine();
}
static void bogosort( int [] arr, int N)
{
while (!is_sorted(arr, N)) {
next_permutation(arr, N);
}
}
static bool is_sorted( int [] arr, int N)
{
for ( int i = 0; i < N - 1; ++i) {
if (arr[i] > arr[i + 1]) {
return false ;
}
}
return true ;
}
static void next_permutation( int [] arr, int N)
{
int i = N - 1;
while (i > 0 && arr[i - 1] >= arr[i]) {
i--;
}
if (i <= 0) {
Array.Reverse(arr, 0, N);
return ;
}
int j = N - 1;
while (arr[j] <= arr[i - 1]) {
j--;
}
int temp = arr[i - 1];
arr[i - 1] = arr[j];
arr[j] = temp;
j = N - 1;
while (i < j) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
}
|
Javascript
let arr = [8, 9, 1, 4, 3];
function bogosort(arr) {
while (!arr.every((val, i) => (i === arr.length - 1) ? true : val <= arr[i + 1])) {
arr.sort(() => Math.random() - 0.5);
}
}
bogosort(arr);
console.log( "Array after sorting" , arr);
|
Output
Array after sorting 1 3 4 8 9
Time Complexity:
- Base Case: O(N)
- Average Case: O(N!)
- Worst Case: O(N!)
Example 2:
C++
#include <bits/stdc++.h>
using namespace std;
bool isSorted( int a[], int N)
{
while (--N > 1) {
if (a[N] < a[N - 1])
return false ;
}
return true ;
}
void shuffle( int a[], int N)
{
for ( int i = 0; i < N; i++)
swap(a[i], a[ rand () % N]);
}
void bogosort( int a[], int N)
{
while (!isSorted(a, N)) {
shuffle(a, N);
}
}
void printArray( int a[], int N)
{
for ( int i = 0; i < N; i++) {
printf ( "%d " , a[i]);
}
printf ( "\n" );
}
int main()
{
int a[] = { 3, 2, 5, 1, 0, 4 };
int N = sizeof a / sizeof a[0];
bogosort(a, N);
printf ( "Array after sorting:" );
printArray(a, N);
return 0;
}
|
Java
import java.util.*;
public class GFG
{
static boolean isSorted( int [] a, int N)
{
while (--N > 0 ) {
if (a[N] < a[N - 1 ])
return false ;
}
return true ;
}
static void shuffle( int [] a, int N)
{
Random rnd = new Random();
for ( int i = 0 ; i < N; i++) {
int y = rnd.nextInt();
y = (((y) % N) + N) % N;
int temp = a[i];
a[i] = a[y];
a[y] = temp;
}
}
static void bogosort( int [] a, int N)
{
while (isSorted(a, N) == false ) {
shuffle(a, N);
}
}
static void printArray( int [] a, int N)
{
for ( int i = 0 ; i < N; i++) {
System.out.print(a[i] + " " );
}
}
public static void main(String[] args)
{
int [] a = { 3 , 2 , 5 , 1 , 0 , 4 };
int N = 6 ;
bogosort(a, N);
System.out.print( "Array after sorting:" );
printArray(a, N);
}
}
|
Python3
import random
def isSorted(a,N):
while (N > 1 ):
N = N - 1
if (a[N] < a[N - 1 ]):
return False
return True
def shuffle(a, N):
for i in range ( 0 , N):
r = random.randint( 0 ,N - 1 )
a[i], a[r] = a[r], a[i]
def bogosort(a, N):
while ( not isSorted(a, N)):
shuffle(a, N)
def printArray(a, N):
for i in range (N):
print (a[i], end = " " )
print ()
a = [ 3 , 2 , 5 , 1 , 0 , 4 ]
N = len (a)
bogosort(a,N)
print ( "Array after sorting:" ,end = "")
printArray(a, N)
|
C#
using System;
class GfG
{
static bool isSorted( int [] a, int N)
{
while (--N > 1) {
if (a[N] < a[N - 1])
return false ;
}
return true ;
}
static void shuffle( int [] a, int N)
{
Random rnd = new Random();
for ( int i = 0; i < N; i++) {
int y = rnd.Next() + 1;
y = y % N;
int temp = a[i];
a[i] = a[y];
a[y] = temp;
}
}
static void bogosort( int [] a, int N)
{
while (isSorted(a, N) == false ) {
shuffle(a, N);
}
}
static void printArray( int [] a, int N)
{
for ( int i = 0; i < N; i++) {
Console.Write(a[i] + " " );
}
}
static void Main()
{
int [] a = { 3, 2, 5, 1, 0, 4 };
int N = 6;
bogosort(a, N);
Console.Write( "Array after sorting:" );
printArray(a, N);
}
}
|
Javascript
<script>
function isSorted(a, N)
{
while (--N > 1) {
if (a[N] < a[N - 1])
return false ;
}
return true ;
}
function shuffle(a, N)
{
for (let i = 0; i < N; i++)
{
let y = Math.floor((Math.random() * 100) + 1);
y= y%N;
let temp= a[i];
a[i]= a[y];
a[y]= temp;
}
}
function bogosort(a, N)
{
while (!isSorted(a, N)) {
shuffle(a, N);
}
}
function printArray(a, N)
{
document.write(a);
}
let a = [ 3, 2, 5, 1, 0, 4 ];
let N = 6;
bogosort(a, N);
document.write( "Array after sorting:" );
printArray(a, N);
</script>
|
Output
Array after sorting:0 1 2 3 4 5
Time Complexity:
- Base Case: O(N)
- Average Case: O(N*N!)
- Worst Case: O(∞)
Clearly, in the worst situation, Bogo sort using random shuffle takes an infinite amount of time to sort an array, and we may say that this is the slowest sorting algorithm. But the thing about Bogo Sort is that it violates some rules in Complexity Analysis. One of the rules is that you actually have to progress towards a goal. You can’t just obviously waste time for example by putting delay loops. The Slow Sort or stooge sort algorithm actually never makes a wrong move. Once it swaps two nodes the nodes will be in the correct order relative to each other and their order will not be reversed.
Similar Reads
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
When to use each Sorting Algorithms | Set 2
Sorting is the process of arranging a set of data in a specific order, which may be numerical (ascending, descending) or lexicographical (alphabetical) order. Why Sorting Is Required? Sorting is very essential when there is a need to highly optimize the searching algorithm. For example, let's assume
5 min read
When to use each Sorting Algorithm
A sorting algorithm is an algorithm that makes the input data set arranged in a certain order. The fundamental task is to put the items in the desired order so that the records are re-arranged for making searching easier. Below is one by one description of when to use which sorting algorithm for bet
4 min read
Time Complexities of all Sorting Algorithms
The efficiency of an algorithm depends on two parameters: Time ComplexityAuxiliary SpaceBoth are calculated as the function of input size(n). One important thing here is that despite these parameters, the efficiency of an algorithm also depends upon the nature and size of the input. Time Complexity:
2 min read
Hybrid Sorting Algorithms
Hybrid sorting algorithms combine two or more standard sorting techniques to optimize performance. For example, Insertion sort works well for small inputs and Quick Sort for large and IntroSort (A Hybrid Sorting Algorithm) uses these properties for using Quick Sort while the input is large and switc
2 min read
Selection Algorithms
Selection Algorithm is an algorithm for finding the kth smallest (or largest) number in a list or an array. That number is called the kth order statistic. It includes the various cases for finding the minimum, maximum and median elements in a list or an array. For finding the minimum (or maximum) el
4 min read
Classification of Sorting Algorithms
Sorting is an algorithm which arranges the elements of a given list in a particular order [ascending or descending]. Sorting algorithms are categorized on the following basis - By number of comparisons :Comparison-based sorting algorithms check the elements of the list by key comparison operation an
3 min read
Stable and Unstable Sorting Algorithms
Stability is mainly essential when we have key-value pairs with duplicate keys possible (like people's names as keys and their details as values). And we wish to sort these objects by keys. What is a stable sorting algorithm? A sorting algorithm is said to be stable if two objects with equal keys ap
3 min read
Hash Sort Algorithm
There have always been arguments about how can be a sorting algorithm of linear time complexity be achieved, as all the traditional sorting algorithms are at least of the order of O(N*log(N)) in worst and cases. The reason for the difficulty in achieving linearly proportional time complexity in a so
15+ min read
Cartesian Tree Sorting
Cartesian Sort is an Adaptive Sorting as it sorts the data faster if data is partially sorted. In fact, there are very few sorting algorithms that make use of this fact. For example consider the array {5, 10, 40, 30, 28}. The input data is partially sorted too as only one swap between â40â and â28â
15+ min read