import random
def insertion_sort(a):
""" Returns the sorted version of 'a'
"""
for i, _ in enumerate(a):
for j in range(i):
if a[i] < a[j]:
a[i], a[j] = a[j], a[i]
return a
def quick_sort(a):
""" Returns the sorted version of 'a'
Quick sort - find a pivot element and return
quick-sorted elements less than pivot +
pivot +
quick-sorted elements greater than pivot.
*** Following implementation is not optimal in space ***
"""
if len(a) <= 0:
return a
# use first element as pivot - not so superior, but doesn't matter.
pivot = a[0]
left = [x for x in a[1:] if x <= pivot]
right = [x for x in a[1:] if x > pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
def quick_sort_helper(a, _min, _max):
if _max <= _min:
return a
# pick a random pivot element
_piv = partition(a, _min, _max)
quick_sort_helper(a, _min, _piv-1)
quick_sort_helper(a, _piv+1, _max)
return a
def partition(a, _min, _max):
"""
1. Put the pivot in its position
2. Partition the array in place so that all elements less than pivot
are arranged to left of it and vice-versa
"""
_piv = random.randint(_min, _max)
pivot = a[_piv]
i = _min+1 # pivot will be put in first position
j = _max
a[_piv], a[_min] = a[_min], a[_piv]
while True:
while (i <= j) and (a[i] <= pivot):
i += 1
while (j >= i) and (a[j] > pivot):
j -= 1
if i < j:
a[i], a[j] = a[j], a[i]
else:
break
a[_min], a[j] = a[j], a[_min]
return j
def quick_sort_opt(a):
""" Returns the sorted version of 'a'
Space efficient.
"""
if len(a) <= 0:
return a
return quick_sort_helper(a, 0, len(a)-1)
if __name__ == "__main__":
print(insertion_sort([4, 3, 2, 1]))
print(insertion_sort([10,3,6,1,2,-4,7,23,22,21]))
print(insertion_sort(list('INSERTIONSORT')))
print(quick_sort([4, 3, 2, 1]))
print(quick_sort(list('insertionsort')))
print(partition([4,3,2,1], 0, 3))
print(partition([6, 8, 6, 7, 2, 3], 0, 5))
print(quick_sort_opt([4, 3, 2, 1]))
print(quick_sort_opt(list('insertionsort')))
print(quick_sort_opt([6, 8, 6, 7, 2, 3]))
print(quick_sort_opt([2]*8))
print("In main - Hello world!")
No comments:
Post a Comment