Cycle Sort is an in-place, comparison-based sorting algorithm that is optimal in terms of the number of writes to the original array. It is particularly useful when memory write operations are expensive because it minimizes the number of writes. Cycle Sort achieves this by determining the correct position of each element in the sorted array and only writing it once to its correct position.
def cycle_sort(arr):
writes = 0 # To count the number of writes
# Loop through the array to find cycles to rotate
for cycle_start in range(0, len(arr) - 1):
item = arr[cycle_start]
# Find where to put the item
pos = cycle_start
for i in range(cycle_start + 1, len(arr)):
if arr[i] < item:
pos += 1
# If the item is already in the correct position
if pos == cycle_start:
continue
# Ignore all duplicate elements
while item == arr[pos]:
pos += 1
# Put the item to its right position
if pos != cycle_start:
arr[pos], item = item, arr[pos]
writes += 1
# Rotate the rest of the cycle
while pos != cycle_start:
pos = cycle_start
for i in range(cycle_start + 1, len(arr)):
if arr[i] < item:
pos += 1
while item == arr[pos]:
pos += 1
if item != arr[pos]:
arr[pos], item = item, arr[pos]
writes += 1
return arr, writes
# Example usage
arr = [4, 3, 2, 1]
sorted_arr, num_writes = cycle_sort(arr)
print("Sorted array is:", sorted_arr)
print("
def cycle_sort(arr):
cycle_sort is defined to take a single list arr as its parameter. writes = 0 # To count the number of writes
writes is initialized to count the number of write operations performed. for cycle_start in range(0, len(arr) - 1):
item = arr[cycle_start]
item holds the value of the current element at cycle_start. pos = cycle_start
for i in range(cycle_start + 1, len(arr)):
if arr[i] < item:
pos += 1
pos) for item by counting the number of elements that are less than item. if pos == cycle_start:
continue
pos is equal to cycle_start, it means item is already in the correct position, so we continue to the next cycle. while item == arr[pos]:
pos += 1
pos until it finds a unique position for item. if pos != cycle_start:
arr[pos], item = item, arr[pos]
writes += 1
item is placed in its correct position, and the displaced element becomes the new item.writes is incremented. while pos != cycle_start:
pos = cycle_start
for i in range(cycle_start + 1, len(arr)):
if arr[i] < item:
pos += 1
while item == arr[pos]:
pos += 1
if item != arr[pos]:
arr[pos], item = item, arr[pos]
writes += 1
writes is incremented for each write operation. return arr, writes
arr and the number of write operations writes are returned.arr = [4, 3, 2, 1]
sorted_arr, num_writes = cycle_sort(arr)
print("Sorted array is:", sorted_arr)
print("Number of writes:", num_writes)
arr is sorted using the cycle_sort function, and the sorted list along with the number of write operations is printed.Sorted array is: [1, 2, 3, 4]
Number of writes: 4