TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
slow_sort.cpp
1
// Returns the sorted vector after performing SlowSort
2
// It is a sorting algorithm that is of humorous nature and not useful.
3
// It's based on the principle of multiply and surrender, a tongue-in-cheek joke
4
// of divide and conquer. It was published in 1986 by Andrei Broder and Jorge
5
// Stolfi in their paper Pessimal Algorithms and Simplexity Analysis. This
6
// algorithm multiplies a single problem into multiple subproblems It is
7
// interesting because it is provably the least efficient sorting algorithm that
8
// can be built asymptotically, and with the restriction that such an algorithm,
9
// while being slow, must still all the time be working towards a result.
10
11
#include <iostream>
12
13
void
SlowSort(
int
a[],
int
i,
int
j) {
14
if
(i >= j)
15
return
;
16
int
m = i + (j - i) / 2;
// midpoint, implemented this way to avoid
17
// overflow
18
int
temp;
19
SlowSort(a, i, m);
20
SlowSort(a, m + 1, j);
21
if
(a[j] < a[m]) {
22
temp = a[j];
// swapping a[j] & a[m]
23
a[j] = a[m];
24
a[m] = temp;
25
}
26
SlowSort(a, i, j - 1);
27
}
28
29
// Sample Main function
30
31
int
main
() {
32
int
size;
33
std::cout <<
"\nEnter the number of elements : "
;
34
35
std::cin >> size;
36
37
int
*arr =
new
int
[size];
38
39
std::cout <<
"\nEnter the unsorted elements : "
;
40
41
for
(
int
i = 0; i < size; ++i) {
42
std::cout <<
"\n"
;
43
std::cin >> arr[i];
44
}
45
46
SlowSort(arr, 0, size);
47
48
std::cout <<
"Sorted array\n"
;
49
50
for
(
int
i = 0; i < size; ++i) {
51
std::cout << arr[i] <<
" "
;
52
}
53
54
delete
[] arr;
55
return
0;
56
}
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
sorting
slow_sort.cpp
Generated by
1.12.0