38std::vector<T>
cycleSort(
const std::vector<T> &in_arr) {
39 std::vector<T> arr(in_arr);
40 for (
int cycle_start = 0; cycle_start <= arr.size() - 1; cycle_start++) {
42 T item = arr[cycle_start];
46 int pos = cycle_start;
47 for (
int i = cycle_start + 1; i < arr.size(); i++) {
54 if (pos == cycle_start) {
59 while (item == arr[pos]) pos += 1;
60 if (pos == cycle_start) {
63 std::swap(item, arr[pos]);
66 while (pos != cycle_start) {
69 for (
size_t i = cycle_start + 1; i < arr.size(); i++) {
75 while (item == arr[pos]) pos += 1;
76 if (item == arr[pos]) {
79 std::swap(item, arr[pos]);
95 std::vector<uint32_t> array1 = {4, 3, 2, 1};
96 std::cout <<
"Test 1... ";
97 std::vector<uint32_t> arr1 = sorting::cycle_sort::cycleSort(array1);
98 assert(std::is_sorted(std::begin(arr1), std::end(arr1)));
99 std::cout <<
"passed" << std::endl;
102 std::vector<double> array2 = {4.3, -6.5, -7.4, 0, 2.7, 1.8};
103 std::cout <<
"Test 2... ";
104 std::vector<double> arr2 = sorting::cycle_sort::cycleSort(array2);
105 assert(std::is_sorted(std::begin(arr2), std::end(arr2)));
106 std::cout <<
"passed" << std::endl;
110 std::vector<uint32_t> array3 = {3, 3, 3, 3};
111 std::cout <<
"Test 3... ";
112 std::vector<uint32_t> arr3 = sorting::cycle_sort::cycleSort(array3);
113 assert(std::is_sorted(std::begin(arr3), std::end(arr3)));
114 std::cout <<
"passed" << std::endl;
117 std::vector<uint32_t> array4 = {3, 4, 6, 8, 9, 14};
118 std::cout <<
"Test 4... ";
119 std::vector<uint32_t> arr4 = sorting::cycle_sort::cycleSort(array4);
120 assert(std::is_sorted(std::begin(arr4), std::end(arr4)));
121 std::cout <<
"passed" << std::endl;