Last active
August 29, 2015 14:07
-
-
Save prat0318/9b9fd7fce843ba260bcf to your computer and use it in GitHub Desktop.
cycle sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def cycle_sort(arr): | |
writes = 0 | |
for cycle_start in xrange(len(arr)): | |
item = arr[cycle_start] | |
print "Item picked :%s index: %s [A: %s]" % (item, cycle_start, arr) | |
pos = cycle_start | |
for i in xrange(cycle_start + 1, len(arr)): | |
if arr[i] < item: | |
pos += 1 | |
print "Actual position: %s [A: %s]" % (pos, arr) | |
if pos == cycle_start: | |
continue | |
while item == arr[pos]: | |
pos += 1 | |
arr[pos], item = item, arr[pos] | |
writes += 1 | |
print "Swapped Item picked :%s index: %s [A: %s]" % (item, pos, arr) | |
while pos != cycle_start: | |
pos = cycle_start | |
for i in xrange(cycle_start + 1, len(arr)): | |
if(arr[i] < item): | |
pos += 1 | |
print "New Actual position: %s [A: %s]" % (pos, arr) | |
while item == arr[pos]: | |
pos += 1 | |
arr[pos], item = item, arr[pos] | |
print "New Swapped Item picked :%s index: %s [A: %s]" % (item, pos, arr) | |
writes += 1 | |
return writes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
a = [2,3,4,5,1]
:a=[4,3,2,1]
: