TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
stooge_sort.cpp
Go to the documentation of this file.
1
16#include <vector>
17#include <cassert>
18#include <algorithm>
19#include <iostream>
20
28void stoogeSort(std::vector<int>* L, size_t i, size_t j) {
29 if (i >= j) {
30 return;
31 }
32 if ((*L)[i] > (*L)[j]) {
33 std::swap((*L)[i], (*L)[j]);
34 }
35 if (j - i > 1) {
36 size_t third = (j - i + 1) / 3;
37 stoogeSort(L, i, j - third);
38 stoogeSort(L, i + third, j);
39 stoogeSort(L, i, j - third);
40 }
41}
42
47void test1() {
48 std::vector<int> L = { 8, 9, 10, 4, 3, 5, 1 };
49 stoogeSort(&L, 0, L.size() - 1);
50 assert(std::is_sorted(std::begin(L), std::end(L)));
51}
52
57void test2() {
58 std::vector<int> L = { -1 };
59 stoogeSort(&L, 0, L.size() - 1);
60 assert(std::is_sorted(std::begin(L), std::end(L)));
61}
62
67void test3() {
68 std::vector<int> L = { 1, 2, 5, 4, 1, 5 };
69 stoogeSort(&L, 0, L.size() - 1);
70 assert(std::is_sorted(std::begin(L), std::end(L)));
71}
72
79int main() {
80 test1();
81 test2();
82 test3();
83
84 std::cout << "All tests have successfully passed!\n";
85 return 0;
86}
void test2()
Function to test sorting algorithm, one element.
void test1()
Function to test sorting algorithm.
void test3()
Function to test sorting algorithm, repeating elements.
void stoogeSort(std::vector< int > *L, size_t i, size_t j)
for IO operations
int main()
Main function.