From dafe60132834cc137f5750130dca081ab0f4996c Mon Sep 17 00:00:00 2001 From: Jaroslav Urban <42768686+JaroslavUrbann@users.noreply.github.com> Date: Sun, 7 Oct 2018 11:11:00 +0200 Subject: [PATCH] Create cycleSort --- sorting/Python/cycleSort | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 sorting/Python/cycleSort diff --git a/sorting/Python/cycleSort b/sorting/Python/cycleSort new file mode 100644 index 0000000..aac3367 --- /dev/null +++ b/sorting/Python/cycleSort @@ -0,0 +1,40 @@ +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 +