📜  最慢的排序算法

📅  最后修改于: 2021-04-22 08:38:29             🧑  作者: Mango

使用排序算法根据上的元素运算符重新排列给定阵列或列表元素。运算符用于决定在相应的数据结构中的元素的新的订单。但是下面是一些最慢的排序算法:

Stooge排序: Stooge排序是一种递归排序算法。它以递归方式对数组进行分割和排序。以下是Stooge Sort的步骤:

  • 如果索引0处的值大于最后一个索引处的值,请交换它们。
  • 如果数组中的元素数大于两个:
    • 为数组的初始2 / 3rd元素递归调用stoogesort函数。
    • 递归地为数组的最后2 / 3rd个元素调用stoogesort函数。
    • 再次递归调用初始2 / 3rd元素的stoogesort函数,以确认结果数组是否已排序。
  • 打印排序后的数组。

下面是上述方法的实现:

C++
// C++ program for the stooge sort
#include 
using namespace std;
 
// Function to implement stooge sort
void stoogesort(int arr[], int l, int h)
{
    // Base Case
    if (l >= h)
        return;
 
    // If first element is smaller than
    // last element, swap them
    if (arr[l] > arr[h])
        swap(arr[l], arr[h]);
 
    // If there are more than 2 elements
    // in the array
    if (h - l + 1 > 2) {
        int t = (h - l + 1) / 3;
 
        // Recursively sort the first
        // 2/3 elements
        stoogesort(arr, l, h - t);
 
        // Recursively sort the last
        // 2/3 elements
        stoogesort(arr, l + t, h);
 
        // Recursively sort the first
        // 2/3 elements again
        stoogesort(arr, l, h - t);
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 4, 5, 3, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    stoogesort(arr, 0, N - 1);
 
    // Display the sorted array
    for (int i = 0; i < N; i++) {
        cout << arr[i] << " ";
    }
 
    return 0;
}


Java
// Java program for the
// stooge sort
class GFG{
     
// Function to implement
// stooge sort
static void stoogesort(int arr[],
                       int l, int h)
{
  // Base Case
  if (l >= h)
    return;
 
  // If first element is smaller
  // than last element, swap them
  if (arr[l] > arr[h])
  {
    int temp = arr[l];
    arr[l] = arr[h];
    arr[h] = temp;
  }
 
  // If there are more than
  // 2 elements in the array
  if (h - l + 1 > 2)
  {
    int t = (h - l + 1) / 3;
 
    // Recursively sort the
    // first 2/3 elements
    stoogesort(arr, l, h - t);
 
    // Recursively sort the
    // last 2/3 elements
    stoogesort(arr, l + t, h);
 
    // Recursively sort the
    // first 2/3 elements again
    stoogesort(arr, l, h - t);
  }
}
 
// Driver Code
public static void main(String[] args)
{
  int arr[] = {2, 4, 5, 3, 1};
  int N = arr.length;
 
  // Function Call
  stoogesort(arr, 0, N - 1);
 
  // Display the sorted array
  for (int i = 0; i < N; i++)
  {
    System.out.print(arr[i] + " ");
  }
}
}
 
// This code is contributed by Chitranayal


Python3
# Python3 program for the stooge sort
 
# Function to implement stooge sort
def stoogesort(arr, l, h):
     
    # Base Case
    if (l >= h):
        return
  
    # If first element is smaller than
    # last element, swap them
    if (arr[l] > arr[h]):
        temp = arr[l]
        arr[l] = arr[h]
        arr[h] = temp
 
    # If there are more than 2 elements
    # in the array
    if (h - l + 1 > 2):
        t = (h - l + 1) // 3
  
        # Recursively sort the first
        # 2/3 elements
        stoogesort(arr, l, h - t)
  
        # Recursively sort the last
        # 2/3 elements
        stoogesort(arr, l + t, h)
  
        # Recursively sort the first
        # 2/3 elements again
        stoogesort(arr, l, h - t)
     
# Driver Code
arr = [ 2, 4, 5, 3, 1 ]
N = len(arr)
  
# Function Call
stoogesort(arr, 0, N - 1)
 
# Display the sorted array
for i in range(N):
    print(arr[i], end = " ")
 
# This code is contributed by code_hunt


C#
// C# program for the
// stooge sort
using System;
class GFG{
     
// Function to implement
// stooge sort
static void stoogesort(int []arr,
                       int l, int h)
{
  // Base Case
  if (l >= h)
    return;
 
  // If first element is smaller
  // than last element, swap them
  if (arr[l] > arr[h])
  {
    int temp = arr[l];
    arr[l] = arr[h];
    arr[h] = temp;
  }
 
  // If there are more than
  // 2 elements in the array
  if (h - l + 1 > 2)
  {
    int t = (h - l + 1) / 3;
 
    // Recursively sort the
    // first 2/3 elements
    stoogesort(arr, l, h - t);
 
    // Recursively sort the
    // last 2/3 elements
    stoogesort(arr, l + t, h);
 
    // Recursively sort the
    // first 2/3 elements again
    stoogesort(arr, l, h - t);
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  int []arr = {2, 4, 5, 3, 1};
  int N = arr.Length;
 
  // Function Call
  stoogesort(arr, 0, N - 1);
 
  // Display the sorted array
  for (int i = 0; i < N; i++)
  {
    Console.Write(arr[i] + " ");
  }
}
}
 
// This code is contributed by Princi Singh


C++
// C++ program to implement Slow sort
#include 
using namespace std;
 
// Function for swap two numbers using
// pointers
void swap(int* xp, int* yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
 
// Function that implements Slow Sort
void slowSort(int A[], int i, int j)
{
    // Base Case
    if (i >= j)
        return;
 
    // Middle value
    int m = (i + j) / 2;
 
    // Recursively call with left half
    slowSort(A, i, m);
 
    // Recursively call with right half
    slowSort(A, m + 1, j);
 
    // Swap if first element
    // is lower than second
    if (A[j] < A[m]) {
        swap(&A[j], &A[m]);
    }
 
    // Recursively call with whole
    // array except maximum element
    slowSort(A, i, j - 1);
}
 
// Function to print the array
void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        cout << arr[i] << " ";
    cout << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 6, 8, 9, 4, 12, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    slowSort(arr, 0, N - 1);
 
    // Display the sorted array
    printArray(arr, N);
 
    return 0;
}


Java
// Java program to implement Slow sort
import java.util.*;
 
class GFG
{
 
// Function that implements Slow Sort
static void slowSort(int A[], int i, int j)
{
    // Base Case
    if (i >= j)
        return;
 
    // Middle value
    int m = (i + j) / 2;
 
    // Recursively call with left half
    slowSort(A, i, m);
 
    // Recursively call with right half
    slowSort(A, m + 1, j);
 
    // Swap if first element
    // is lower than second
    if (A[j] < A[m])
    {
        int temp = A[j];
        A[j] = A[m];
        A[m] = temp;
    }
 
    // Recursively call with whole
    // array except maximum element
    slowSort(A, i, j - 1);
}
 
// Function to print the array
static void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        System.out.print(arr[i]+ " ");
    System.out.println();
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 6, 8, 9, 4, 12, 1 };
    int N = arr.length;
 
    // Function call
    slowSort(arr, 0, N - 1);
 
    // Display the sorted array
    printArray(arr, N);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python program to implement Slow sort
 
# Function that implements Slow Sort
def slowSort(A, i, j):
   
    # Base Case
    if (i >= j):
        return;
 
    # Middle value
    m = (i + j) // 2;
 
    # Recursively call with left half
    slowSort(A, i, m);
 
    # Recursively call with right half
    slowSort(A, m + 1, j);
 
    # Swap if first element
    # is lower than second
    if (A[j] < A[m]):
        temp = A[j];
        A[j] = A[m];
        A[m] = temp;
 
    # Recursively call with whole
    # array except maximum element
    slowSort(A, i, j - 1);
 
# Function to prthe array
def printArray(arr, size):
    i = 0;
    for i in range(size):
        print(arr[i], end=" ");
    print();
 
# Driver Code
if __name__ == '__main__':
    arr = [6, 8, 9, 4, 12, 1];
    N = len(arr);
 
    # Function call
    slowSort(arr, 0, N - 1);
 
    # Display the sorted array
    printArray(arr, N);
 
    # This code contributed by gauravrajput1


C#
// C# program to implement Slow sort
using System;
class GFG
{
 
// Function that implements Slow Sort
static void slowSort(int []A, int i, int j)
{
    // Base Case
    if (i >= j)
        return;
 
    // Middle value
    int m = (i + j) / 2;
 
    // Recursively call with left half
    slowSort(A, i, m);
 
    // Recursively call with right half
    slowSort(A, m + 1, j);
 
    // Swap if first element
    // is lower than second
    if (A[j] < A[m])
    {
        int temp = A[j];
        A[j] = A[m];
        A[m] = temp;
    }
 
    // Recursively call with whole
    // array except maximum element
    slowSort(A, i, j - 1);
}
 
// Function to print the array
static void printArray(int []arr, int size)
{
    int i;
    for (i = 0; i < size; i++)
        Console.Write(arr[i] + " ");
    Console.WriteLine();
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 6, 8, 9, 4, 12, 1 };
    int N = arr.Length;
 
    // Function call
    slowSort(arr, 0, N - 1);
 
    // Display the sorted array
    printArray(arr, N);
}
}
 
// This code is contributed by 29AjayKumar


C++
// C++ program to implement Sleep sort
#ifdef _WIN32
 
// sleep() function for windows machine
#include 
#else
 
// sleep() function for linux machine
#include 
#endif
#include 
#include 
#include 
 
using namespace std;
 
// Array for storing the sorted values
vector A;
 
// Function for print the array
void printArray(vector arr, int size)
{
    int i;
    for (i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
}
 
// The instruction set for a thread
void add(int x)
{
    // Temporarily suspend execution
    // of each thread for x amount
    // of seconds
    sleep(x);
 
    // Every thead will wake up after
    // a particular time and push the
    // value in sorted array
    A.push_back(x);
}
 
// Function for Sleep sort
void sleepSort(int arr[], int N)
{
 
    vector threads;
    for (int i = 0; i < N; i++) {
 
        // New threads were launched by
        // using function pointer as
        // callable
        threads.push_back(
            thread(add, arr[i]));
    }
 
    // Waiting for each thread
    // to finish execution
    for (auto& th : threads) {
        th.join();
    }
 
    // Display the sorted array
    cout << "Array after sorting: ";
    printArray(A, A.size());
}
 
// Driver Code
int main()
{
    int arr[] = { 8, 9, 1, 4, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // sleep_sort function call
    sleepSort(arr, N);
 
    return 0;
}
 
// To run compile using -pthread
// {  1, 3, 4, 8, 9}


C++
// C++ program to implement Bogo Sort
// using permutation
#include 
using namespace std;
 
// Function to sort array using bogosort
void bogosort(int arr[], int N)
{
    // Run the loop until
    // array is not sorted
    while (!is_sorted(arr, arr + N)) {
 
        // All possible permutations
        next_permutation(arr, arr + N);
    }
}
// Driver Code
int main()
{
 
    int arr[] = { 8, 9, 1, 4, 3 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    bogosort(arr, N);
 
    // Display the sorted array
    cout << "Array after sorting ";
    for (int i = 0; i < N; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;
 
    return 0;
}


C++
// C++ program to implement Bogo Sort
// using random shuffle
#include 
using namespace std;
 
// Function to check if array is
// sorted or not
bool isSorted(int a[], int N)
{
    while (--N > 1) {
 
        // Break condition for
        // unsorted array
        if (a[N] < a[N - 1])
            return false;
    }
    return true;
}
 
// Function to generate permuatation
// of the array
void shuffle(int a[], int N)
{
    for (int i = 0; i < N; i++)
        swap(a[i], a[rand() % N]);
}
 
// Function to sort array using
// Bogo sort
void bogosort(int a[], int N)
{
    // If array is not sorted
    // then shuffle array again
    while (!isSorted(a, N)) {
 
        shuffle(a, N);
    }
}
 
// Function to print the array
void printArray(int a[], int N)
{
    for (int i = 0; i < N; i++) {
 
        printf("%d ", a[i]);
    }
    printf("\n");
}
 
// Driver Code
int main()
{
    int a[] = { 3, 2, 5, 1, 0, 4 };
    int N = sizeof a / sizeof a[0];
 
    // Function Call
    bogosort(a, N);
    printf("Array after sorting:");
    printArray(a, N);
    return 0;
}


输出:
1 2 3 4 5

时间复杂度: O(N 2.709 )。因此,它甚至比具有时间复杂度O(N 2 )的冒泡排序还要慢。

慢速排序:慢速排序是“乘以并放弃”分而治之的开玩笑的一个例子。慢速排序将数组的最大元素存储在最后一个位置,方法是将数组递归除以一半,然后对每个元素进行比较。然后,它递归地调用不包含先前的最大元素的数组,并将新的最大元素存储在新的最后位置。以下是慢速排序的步骤:

  1. 找到数组的最大值,然后将其放在数组的末尾
    1. 递归地调用slowsort函数以获取前N / 2个元素中的最大值。
    2. 递归调用slowsort函数以获取剩余的N / 2个元素的最大值。
    3. 找到这两个最大值中的最大值,并将其存储在末尾。
    4. 除了最大值以外,递归调用整个数组的slowsort函数。
  2. 打印排序后的数组。

下面是上述方法的实现:

C++

// C++ program to implement Slow sort
#include 
using namespace std;
 
// Function for swap two numbers using
// pointers
void swap(int* xp, int* yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
 
// Function that implements Slow Sort
void slowSort(int A[], int i, int j)
{
    // Base Case
    if (i >= j)
        return;
 
    // Middle value
    int m = (i + j) / 2;
 
    // Recursively call with left half
    slowSort(A, i, m);
 
    // Recursively call with right half
    slowSort(A, m + 1, j);
 
    // Swap if first element
    // is lower than second
    if (A[j] < A[m]) {
        swap(&A[j], &A[m]);
    }
 
    // Recursively call with whole
    // array except maximum element
    slowSort(A, i, j - 1);
}
 
// Function to print the array
void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        cout << arr[i] << " ";
    cout << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 6, 8, 9, 4, 12, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    slowSort(arr, 0, N - 1);
 
    // Display the sorted array
    printArray(arr, N);
 
    return 0;
}

Java

// Java program to implement Slow sort
import java.util.*;
 
class GFG
{
 
// Function that implements Slow Sort
static void slowSort(int A[], int i, int j)
{
    // Base Case
    if (i >= j)
        return;
 
    // Middle value
    int m = (i + j) / 2;
 
    // Recursively call with left half
    slowSort(A, i, m);
 
    // Recursively call with right half
    slowSort(A, m + 1, j);
 
    // Swap if first element
    // is lower than second
    if (A[j] < A[m])
    {
        int temp = A[j];
        A[j] = A[m];
        A[m] = temp;
    }
 
    // Recursively call with whole
    // array except maximum element
    slowSort(A, i, j - 1);
}
 
// Function to print the array
static void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        System.out.print(arr[i]+ " ");
    System.out.println();
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 6, 8, 9, 4, 12, 1 };
    int N = arr.length;
 
    // Function call
    slowSort(arr, 0, N - 1);
 
    // Display the sorted array
    printArray(arr, N);
}
}
 
// This code is contributed by 29AjayKumar

Python3

# Python program to implement Slow sort
 
# Function that implements Slow Sort
def slowSort(A, i, j):
   
    # Base Case
    if (i >= j):
        return;
 
    # Middle value
    m = (i + j) // 2;
 
    # Recursively call with left half
    slowSort(A, i, m);
 
    # Recursively call with right half
    slowSort(A, m + 1, j);
 
    # Swap if first element
    # is lower than second
    if (A[j] < A[m]):
        temp = A[j];
        A[j] = A[m];
        A[m] = temp;
 
    # Recursively call with whole
    # array except maximum element
    slowSort(A, i, j - 1);
 
# Function to prthe array
def printArray(arr, size):
    i = 0;
    for i in range(size):
        print(arr[i], end=" ");
    print();
 
# Driver Code
if __name__ == '__main__':
    arr = [6, 8, 9, 4, 12, 1];
    N = len(arr);
 
    # Function call
    slowSort(arr, 0, N - 1);
 
    # Display the sorted array
    printArray(arr, N);
 
    # This code contributed by gauravrajput1

C#

// C# program to implement Slow sort
using System;
class GFG
{
 
// Function that implements Slow Sort
static void slowSort(int []A, int i, int j)
{
    // Base Case
    if (i >= j)
        return;
 
    // Middle value
    int m = (i + j) / 2;
 
    // Recursively call with left half
    slowSort(A, i, m);
 
    // Recursively call with right half
    slowSort(A, m + 1, j);
 
    // Swap if first element
    // is lower than second
    if (A[j] < A[m])
    {
        int temp = A[j];
        A[j] = A[m];
        A[m] = temp;
    }
 
    // Recursively call with whole
    // array except maximum element
    slowSort(A, i, j - 1);
}
 
// Function to print the array
static void printArray(int []arr, int size)
{
    int i;
    for (i = 0; i < size; i++)
        Console.Write(arr[i] + " ");
    Console.WriteLine();
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 6, 8, 9, 4, 12, 1 };
    int N = arr.Length;
 
    // Function call
    slowSort(arr, 0, N - 1);
 
    // Display the sorted array
    printArray(arr, N);
}
}
 
// This code is contributed by 29AjayKumar
输出:
1 4 6 8 9 12

时间复杂度:

  • 基本情况: O(N ((log N)/(2 + e))其中,e> 0
  • 平均情况: O(N (log(N)/ 2) )

即使是最好的情况也比冒泡排序差。它的效率不如Stooge排序。

睡眠排序:以下是Stooge排序的步骤:

  1. 为输入数组中的每个元素创建不同的线程,然后每个线程休眠一段时间,该时间与相应数组元素的值成比例。
  2. 具有最短睡眠时间的线程首先被唤醒,然后编号被打印,然后是第二个最小的元素,依此类推。
  3. 最大的元素会在很长一段时间后唤醒,然后在最后打印该元素。因此,输出为已排序的输出。

所有这些多线程过程都发生在操作系统的后台和核心

下面是上述方法的实现:

C++

// C++ program to implement Sleep sort
#ifdef _WIN32
 
// sleep() function for windows machine
#include 
#else
 
// sleep() function for linux machine
#include 
#endif
#include 
#include 
#include 
 
using namespace std;
 
// Array for storing the sorted values
vector A;
 
// Function for print the array
void printArray(vector arr, int size)
{
    int i;
    for (i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
}
 
// The instruction set for a thread
void add(int x)
{
    // Temporarily suspend execution
    // of each thread for x amount
    // of seconds
    sleep(x);
 
    // Every thead will wake up after
    // a particular time and push the
    // value in sorted array
    A.push_back(x);
}
 
// Function for Sleep sort
void sleepSort(int arr[], int N)
{
 
    vector threads;
    for (int i = 0; i < N; i++) {
 
        // New threads were launched by
        // using function pointer as
        // callable
        threads.push_back(
            thread(add, arr[i]));
    }
 
    // Waiting for each thread
    // to finish execution
    for (auto& th : threads) {
        th.join();
    }
 
    // Display the sorted array
    cout << "Array after sorting: ";
    printArray(A, A.size());
}
 
// Driver Code
int main()
{
    int arr[] = { 8, 9, 1, 4, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // sleep_sort function call
    sleepSort(arr, N);
 
    return 0;
}
 
// To run compile using -pthread
// {  1, 3, 4, 8, 9}
输出:
Array after sorting 1 3 4 8 9

时间复杂度: O(max(input)+ N)其中,input =数组元素的值

其他算法的时间复杂度取决于数据数量,但对于睡眠排序,则取决于数据量。该算法不适用于负数,因为线程无法在负数的时间内休眠。

Bogo排序:此算法存在两种版本:一种枚举所有排列,直到命中已排序的一种;另一种随机排列的版本,对输入进行随机排列。

范例1:

C++

// C++ program to implement Bogo Sort
// using permutation
#include 
using namespace std;
 
// Function to sort array using bogosort
void bogosort(int arr[], int N)
{
    // Run the loop until
    // array is not sorted
    while (!is_sorted(arr, arr + N)) {
 
        // All possible permutations
        next_permutation(arr, arr + N);
    }
}
// Driver Code
int main()
{
 
    int arr[] = { 8, 9, 1, 4, 3 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    bogosort(arr, N);
 
    // Display the sorted array
    cout << "Array after sorting ";
    for (int i = 0; i < N; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;
 
    return 0;
}
输出:
Array after sorting 1 3 4 8 9

时间复杂度:

  • 基本情况: O(N)
  • 平均情况: O(N!)
  • 最坏的情况: O(N!)

范例2:

C++

// C++ program to implement Bogo Sort
// using random shuffle
#include 
using namespace std;
 
// Function to check if array is
// sorted or not
bool isSorted(int a[], int N)
{
    while (--N > 1) {
 
        // Break condition for
        // unsorted array
        if (a[N] < a[N - 1])
            return false;
    }
    return true;
}
 
// Function to generate permuatation
// of the array
void shuffle(int a[], int N)
{
    for (int i = 0; i < N; i++)
        swap(a[i], a[rand() % N]);
}
 
// Function to sort array using
// Bogo sort
void bogosort(int a[], int N)
{
    // If array is not sorted
    // then shuffle array again
    while (!isSorted(a, N)) {
 
        shuffle(a, N);
    }
}
 
// Function to print the array
void printArray(int a[], int N)
{
    for (int i = 0; i < N; i++) {
 
        printf("%d ", a[i]);
    }
    printf("\n");
}
 
// Driver Code
int main()
{
    int a[] = { 3, 2, 5, 1, 0, 4 };
    int N = sizeof a / sizeof a[0];
 
    // Function Call
    bogosort(a, N);
    printf("Array after sorting:");
    printArray(a, N);
    return 0;
}
输出:
Array after sorting:0 1 2 3 4 5

时间复杂度:

  • 基本情况: O(N)
  • 平均情况: O(N * N!)
  • 最坏的情况: O(∞)

显然,在最坏的情况下,使用随机混洗的Bogo排序会花费无数的时间来对数组进行排序,我们可以说这是最慢的排序算法。但是关于Bogo Sort的事情是,它违反了复杂度分析中的某些规则。规则之一是您实际上必须朝着目标前进。您不能仅仅通过例如放置延迟循环而明显地浪费时间。慢速排序或or行排序算法实际上永远不会犯错。一旦交换了两个节点,这些节点将相对于彼此以正确的顺序排列,并且它们的顺序将不会颠倒。