Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CycleSort #21

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
Binary file added algorithms/.DS_Store
Binary file not shown.
Binary file added algorithms/math/.DS_Store
Binary file not shown.
45 changes: 45 additions & 0 deletions algorithms/sorting/CycleSort.m
Original file line number Diff line number Diff line change
@@ -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