Select Page

# Program for Cycle Sort using Python

by | Jun 16, 2021 | Python Programs

## Introduction

Cycle sort algorithm is an unstable in-place sorting algorithm. Our task is to sort the given array using cycle sort.

## Program

```def sort(arr):

temp = 0

for start in range(0, len(arr) - 1):

ele = arr[start]

# Find the index to place

idx = start

for i in range(start + 1, len(arr)):

if arr[i] < ele:

idx += 1

if idx == start:

continue

while ele == arr[idx]:

idx += 1

arr[idx], ele = ele, arr[idx]

temp += 1

while idx != start:

idx = start

for i in range(start + 1, len(arr)):

if arr[i] < ele:

idx += 1

while ele == arr[idx]:

idx += 1

arr[idx], ele = ele, arr[idx]

temp += 1

return temp

ip_arr = [10, 2, 51, 3]

sort(ip_arr)

print("The sorted array is: ")

for i in range(0, len(ip_arr)):

print(ip_arr[i])```

## Explanation

The steps followed in the above program are:

• Take the first element of the array and find all the elements that are smaller than it.
• Move the element to index = number of elements that are smaller and swap.
• Repeat the above for all the elements in the given array.