-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathCycleSort.m
45 lines (39 loc) · 1.08 KB
/
CycleSort.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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