From 00e10d9250d18933e7792bf0771884cc1099eeec Mon Sep 17 00:00:00 2001 From: acdlee <53183861+acdlee@users.noreply.github.com> Date: Fri, 22 Jan 2021 11:50:42 -0500 Subject: [PATCH] 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 --- sorting/README.md | 2 ++ sorting/python/insertion-sort.py | 30 ++++++++++++++++++++++++++ sorting/python/selection-sort.py | 37 ++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 sorting/python/insertion-sort.py create mode 100644 sorting/python/selection-sort.py diff --git a/sorting/README.md b/sorting/README.md index d0b820d6..e75bfe72 100644 --- a/sorting/README.md +++ b/sorting/README.md @@ -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 diff --git a/sorting/python/insertion-sort.py b/sorting/python/insertion-sort.py new file mode 100644 index 00000000..a72f334b --- /dev/null +++ b/sorting/python/insertion-sort.py @@ -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)) + diff --git a/sorting/python/selection-sort.py b/sorting/python/selection-sort.py new file mode 100644 index 00000000..bab47060 --- /dev/null +++ b/sorting/python/selection-sort.py @@ -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)) \ No newline at end of file