Added Insertion and Selection sort to the python folders. (#22)
* Added Insertion and Selection sort to the python folders. * Loop(s) bound issues resolved; semantics of pseudocode to the range function recognized. Co-authored-by: Christopher Lee <christopherlee@wireless-10-104-179-111.umd.edu>pull/26/head
parent
ec35fca77d
commit
00e10d9250
|
@ -14,6 +14,8 @@
|
|||
### Python
|
||||
|
||||
1. [Bubble Sort](python/bubble-sort.py)
|
||||
2. [Insertion Sort](python/insertion-sort.py)
|
||||
2. [Selection Sort](python/selection-sort.py)
|
||||
|
||||
### JavaScript
|
||||
|
||||
|
|
|
@ -0,0 +1,30 @@
|
|||
"""
|
||||
Analogizing this algorithm with inserting a playing
|
||||
card into your hand, we distinguish the "key" as
|
||||
the inserting card and find the position of that
|
||||
card among the previous j - 1 cards.
|
||||
|
||||
O(n^2) runtime (the deck is sorted in descending order).
|
||||
"""
|
||||
|
||||
def insertionSort(A):
|
||||
N = len(A)
|
||||
|
||||
for j in range(1, N):
|
||||
key = A[j]
|
||||
#insert the key into the sorted sequence A[1, ... , j - 1]
|
||||
i = j - 1
|
||||
while i >= 0 and A[i] > key:
|
||||
A[i + 1] = A[i]
|
||||
i -= 1
|
||||
|
||||
A[i + 1] = key
|
||||
|
||||
|
||||
A = [12, 3, 7, 22, -12, 100, 1]
|
||||
insertionSort(A)
|
||||
|
||||
print("Sorted array: ")
|
||||
for ele in A:
|
||||
print("\t" + str(ele))
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
'''
|
||||
Find the largest element and place that element at the bottom
|
||||
of the list. Repeat for each sub-array.
|
||||
|
||||
O(n^2) time complexity.
|
||||
'''
|
||||
def selectionSort(A):
|
||||
N = len(A)
|
||||
|
||||
for i in range(N - 1, 0, -1):
|
||||
k = 0
|
||||
|
||||
for j in range(1, i + 1):
|
||||
if A[j] > A[k]:
|
||||
k = j
|
||||
swap(A, k, i)
|
||||
|
||||
|
||||
def swap(A, k, i):
|
||||
"""
|
||||
Helper function for swapping elements of the array.
|
||||
"""
|
||||
tmp = A[k]
|
||||
A[k] = A[i]
|
||||
A[i] = tmp
|
||||
|
||||
|
||||
# A = [12, 3, 7, 22, -12, 100, 1]
|
||||
# A = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
|
||||
# A = [4, 1, 3, 9, 7]
|
||||
A = [5, 4, 3, 2, 1]
|
||||
|
||||
selectionSort(A)
|
||||
|
||||
print("Sorted array: ")
|
||||
for ele in A:
|
||||
print("\t" + str(ele))
|
Loading…
Reference in New Issue