Slow Sort.cpp 1.4 KB
Newer Older
N
Naveen Hegde 已提交
1
//Returns the sorted vector after performing SlowSort
Y
yanglbme 已提交
2 3
//It is a sorting algorithm that is of humorous nature and not useful.
//It's based on the principle of multiply and surrender, a tongue-in-cheek joke of divide and conquer.
N
Naveen Hegde 已提交
4 5
//It was published in 1986 by Andrei Broder and Jorge Stolfi in their paper Pessimal Algorithms and Simplexity Analysis.
//This algorithm multiplies a single problem into multiple subproblems
Y
yanglbme 已提交
6
//It is interesting because it is provably the least efficient sorting algorithm that can be built asymptotically,
N
Naveen Hegde 已提交
7 8
//and with the restriction that such an algorithm, while being slow, must still all the time be working towards a result.

Y
yanglbme 已提交
9
#include <iostream>
N
Naveen Hegde 已提交
10 11 12 13
using namespace std;

void SlowSort(int a[], int i, int j)
{
Y
yanglbme 已提交
14
  if (i >= j)
N
Naveen Hegde 已提交
15
    return;
Y
yanglbme 已提交
16
  int m = i + (j - i) / 2; //midpoint, implemented this way to avoid overflow
N
Naveen Hegde 已提交
17 18 19
  int temp;
  SlowSort(a, i, m);
  SlowSort(a, m + 1, j);
Y
yanglbme 已提交
20
  if (a[j] < a[m])
N
Naveen Hegde 已提交
21
  {
Y
yanglbme 已提交
22 23 24
    temp = a[j]; //swapping a[j] & a[m]
    a[j] = a[m];
    a[m] = temp;
N
Naveen Hegde 已提交
25 26 27 28 29 30 31 32
  }
  SlowSort(a, i, j - 1);
}

//Sample Main function

int main()
{
Y
yanglbme 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
  int size;
  cout << "\nEnter the number of elements : ";

  cin >> size;

  int arr[size];

  cout << "\nEnter the unsorted elements : ";

  for (int i = 0; i < size; ++i)
  {
    cout << "\n";
    cin >> arr[i];
  }

  SlowSort(arr, 0, size);

  cout << "Sorted array\n";

  for (int i = 0; i < size; ++i)
  {
    cout << arr[i] << " ";
  }
  return 0;
N
Naveen Hegde 已提交
57
}