diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..8b26fa1 Binary files /dev/null and b/.DS_Store differ diff --git a/algorithms/.DS_Store b/algorithms/.DS_Store new file mode 100644 index 0000000..5e1e7f8 Binary files /dev/null and b/algorithms/.DS_Store differ diff --git a/algorithms/math/.DS_Store b/algorithms/math/.DS_Store new file mode 100644 index 0000000..c321d6f Binary files /dev/null and b/algorithms/math/.DS_Store differ diff --git a/algorithms/sorting/CycleSort.m b/algorithms/sorting/CycleSort.m new file mode 100644 index 0000000..55c771d --- /dev/null +++ b/algorithms/sorting/CycleSort.m @@ -0,0 +1,45 @@ +function cycleSort(arr) + n = length(arr); + + for cycleStart = 1:n-1 + item = arr(cycleStart); + pos = cycleStart; + + % Find the position to place the current item + for i = cycleStart+1:n + if arr(i) < item + pos = pos + 1; + end + end + + % Skip if the item is already in its correct position + if pos == cycleStart + continue; + end + + % Place the item in its correct position + while item == arr(pos) + pos = pos + 1; + end + temp = arr(pos); + arr(pos) = item; + item = temp; + + % Rotate the rest of the cycle + while pos ~= cycleStart + pos = cycleStart; + for i = cycleStart+1:n + if arr(i) < item + pos = pos + 1; + end + end + + while item == arr(pos) + pos = pos + 1; + end + temp = arr(pos); + arr(pos) = item; + item = temp; + end + end +end