Add Python doctest to insertion-sort.py (#165)
* Add Python doctest to insertion-sort.py * if __name__ == "__main__": * Update insertion-sort.pypull/173/head
parent
66c65383fb
commit
bd860a57a4
|
@ -6,25 +6,27 @@ card among the previous j - 1 cards.
|
||||||
|
|
||||||
O(n^2) runtime (the deck is sorted in descending order).
|
O(n^2) runtime (the deck is sorted in descending order).
|
||||||
"""
|
"""
|
||||||
|
arr = [12, 3, 7, 22, -12, 100, 1]
|
||||||
|
|
||||||
def insertionSort(A):
|
|
||||||
N = len(A)
|
|
||||||
|
|
||||||
for j in range(1, N):
|
def insertion_sort(arr):
|
||||||
key = A[j]
|
"""
|
||||||
#insert the key into the sorted sequence A[1, ... , j - 1]
|
>>> insertion_sort(arr)
|
||||||
|
>>> arr
|
||||||
|
[-12, 1, 3, 7, 12, 22, 100]
|
||||||
|
"""
|
||||||
|
for j in range(1, len(arr)):
|
||||||
|
key = arr[j]
|
||||||
|
# insert the key into the sorted sequence arr[1, ... , j - 1]
|
||||||
i = j - 1
|
i = j - 1
|
||||||
while i >= 0 and A[i] > key:
|
while i >= 0 and arr[i] > key:
|
||||||
A[i + 1] = A[i]
|
arr[i + 1] = arr[i]
|
||||||
i -= 1
|
i -= 1
|
||||||
|
arr[i + 1] = key
|
||||||
A[i + 1] = key
|
|
||||||
|
|
||||||
|
|
||||||
A = [12, 3, 7, 22, -12, 100, 1]
|
if __name__ == "__main__":
|
||||||
insertionSort(A)
|
insertion_sort(arr)
|
||||||
|
print("Sorted array: ")
|
||||||
print("Sorted array: ")
|
for ele in arr:
|
||||||
for ele in A:
|
print(f"\t{ele}")
|
||||||
print("\t" + str(ele))
|
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue