Open In App

Python Program for Cycle Sort

Last Updated : 28 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Cycle sort is an in-place sorting Algorithm, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array.

  • It is optimal in terms of number of memory writes. It minimizes the number of memory writes to sort (Each value is either written zero times, if it’s already in its correct position, or written one time to its correct position.)
  • It is based on the idea that array to be sorted can be divided into cycles. Cycles can be visualized as a graph. We have n nodes and an edge directed from node i to node j if the element at i-th index must be present at j-th index in the sorted array. Cycle in arr[] = {4, 5, 2, 1, 5} cycle-sort Cycle in arr[] = {4, 3, 2, 1} cyclc-sort2

We one by one consider all cycles. We first consider the cycle that includes first element. We find correct position of first element, place it at its correct position, say j. We consider old value of arr[j] and find its correct position, we keep doing this till all elements of current cycle are placed at correct position, i.e., we don\’t come back to cycle starting point.

Python3




# Python program to implement cycle sort
 
def cycleSort(array):
writes = 0
 
# Loop through the array to find cycles to rotate.
for cycleStart in range(0, len(array) - 1):
    item = array[cycleStart]
     
    # Find where to put the item.
    pos = cycleStart
    for i in range(cycleStart + 1, len(array)):
    if array[i] < item:
        pos += 1
     
    # If the item is already there, this is not a cycle.
    if pos == cycleStart:
    continue
     
    # Otherwise, put the item there or right after any duplicates.
    while item == array[pos]:
    pos += 1
    array[pos], item = item, array[pos]
    writes += 1
     
    # Rotate the rest of the cycle.
    while pos != cycleStart:
     
    # Find where to put the item.
    pos = cycleStart
    for i in range(cycleStart + 1, len(array)):
        if array[i] < item:
        pos += 1
     
    # Put the item there or right after any duplicates.
    while item == array[pos]:
        pos += 1
    array[pos], item = item, array[pos]
    writes += 1
 
return writes
 
# driver code
arr = [1, 8, 3, 9, 10, 10, 2, 4 ]
n = len(arr)
cycleSort(arr)
 
print("After sort : ")
for i in range(0, n) :
    print(arr[i], end = \' \')


Output:

After sort : 
1 2 3 4 8 9 10 10

Time Complexity: O(n2)
Auxiliary Space: O(1)

Please refer complete article on Cycle Sort for more details!



Previous Article
Next Article

Similar Reads

Sort an Array which contain 1 to N values in O(N) using Cycle Sort
Prerequisite: Cycle SortGiven an array arr[] of elements from 1 to N, the task is to sort the given array in O(N) time.Examples: Input: arr[] = { 2, 1, 5, 4, 3} Output: 1 2 3 4 5 Explanation: Since arr[0] = 2 is not at correct position, then swap arr[0] with arr[arr[0] - 1] Now array becomes: arr[] = {1, 2, 5, 4, 3}Now arr[2] = 5 is not at correct
6 min read
Tag sort or Bucket sort or Bin sort in Python
Tag sort, also known as Bucket sort or Bin sort, is a non-comparison based sorting algorithm that distributes elements of an array into a number of "buckets", and then sorts each bucket individually. Tag sort or Bucket sort or Bin sort Algorithm:Determine Range:Find the maximum and minimum values in the input array to determine the range of tags ne
2 min read
C++ Program for Cycle Sort
Cycle sort is an in-place sorting Algorithm, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array. It is optimal in terms of number of memory writes. It minimizes the number of memory writes to sort (Each value is either written zero times, if it’s already in its co
3 min read
Java Program for Cycle Sort
Cycle sort is an in-place sorting Algorithm, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array. It is optimal in terms of number of memory writes. It minimizes the number of memory writes to sort (Each value is either written zero times, if it’s already in its co
3 min read
Comparison among Bubble Sort, Selection Sort and Insertion Sort
Bubble Sort, Selection Sort, and Insertion Sort are simple sorting algorithms that are commonly used to sort small datasets or as building blocks for more complex sorting algorithms. Here's a comparison of the three algorithms: Bubble Sort:Time complexity: O(n^2) in the worst and average cases, O(n) in the best case (when the input array is already
15 min read
Detect cycle in Directed Graph using Topological Sort
Given a Directed Graph consisting of N vertices and M edges and a set of Edges[][], the task is to check whether the graph contains a cycle or not using Topological sort. Topological sort of directed graph is a linear ordering of its vertices such that, for every directed edge U -&gt; V from vertex U to vertex V, U comes before V in the ordering. E
9 min read
Cycle Sort
Cycle sort is an in-place, unstable sorting algorithm that is particularly useful when sorting arrays containing elements with a small range of values. It was developed by W. D. Jones and published in 1963. The basic idea behind cycle sort is to divide the input array into cycles, where each cycle consists of elements that belong to the same positi
15+ min read
Python Program for Odd-Even Sort / Brick Sort
This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd indexed elements and in the even phase, we perform a bubble sort on even i
2 min read
Python Program for Detect Cycle in a Directed Graph
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains three cycles 0->2->0, 0->1->2->0 and 3->3, so your function must return true. Recommended: Please solve it on "PRACTICE" first, before
2 min read
Python Program for Detect Cycle in Graph using DSU
Prerequisite: Introduction to Disjoint Set Given an undirected graph, The task is to detect if there is a cycle in the given graph. Example: Input: N = 4, E = 4  Output: Yes Explanation: The diagram clearly shows a cycle 0 to 2 to 1 to 0 Input: N = 4, E = 3 Output: No Explanation: There is no cycle in the given graph Python Program for Detect Cycle
4 min read