From cbedad1dc4670cbc451a77711d306be9e61f196c Mon Sep 17 00:00:00 2001 From: Abhishek-Verma75230 <115094713+Abhishek-Verma75230@users.noreply.github.com> Date: Fri, 14 Oct 2022 21:29:32 +0530 Subject: [PATCH] cycle sort in python. cycle sort in python. --- Cycle_Sort.py | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Cycle_Sort.py diff --git a/Cycle_Sort.py b/Cycle_Sort.py new file mode 100644 index 0000000..fd57ce8 --- /dev/null +++ b/Cycle_Sort.py @@ -0,0 +1,52 @@ +# 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 = \' \') + +