From 23fdbf71b07515d3163f192c2267b48e379c0ade Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=8Dtalo=20Vin=C3=ADcius?= <39673124+italovinicius18@users.noreply.github.com> Date: Sun, 4 Oct 2020 12:51:35 -0300 Subject: [PATCH] Selection and Insertion sort in Python --- Sorting/InsertionSort.py | 27 +++++++++++++++++++++++++++ Sorting/SelectionSort.py | 27 +++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 Sorting/InsertionSort.py create mode 100644 Sorting/SelectionSort.py diff --git a/Sorting/InsertionSort.py b/Sorting/InsertionSort.py new file mode 100644 index 0000000..6a6b5bb --- /dev/null +++ b/Sorting/InsertionSort.py @@ -0,0 +1,27 @@ +# This is the Python version of Insertion Sort +# Code is contributed by: Italo Vinicius. +# +# Insertion sort is an Sorting Algorithm which takes compelxity: O(n²) + +# Function to do insertion sort +def insertionSort(arr): + + # Traverse through 1 to len(arr) + for i in range(1, len(arr)): + + key = arr[i] + + # Move elements of arr[0..i-1], that are + # greater than key, to one position ahead + # of their current position + j = i-1 + while j >= 0 and key < arr[j] : + arr[j + 1] = arr[j] + j -= 1 + arr[j + 1] = key + +if __name__ == "__main__": + arr = list(map(int,input().split())) + insertionSort(arr) + + print(' '.join(str(x) for x in arr)) \ No newline at end of file diff --git a/Sorting/SelectionSort.py b/Sorting/SelectionSort.py new file mode 100644 index 0000000..729c1f0 --- /dev/null +++ b/Sorting/SelectionSort.py @@ -0,0 +1,27 @@ +# This is the Python version of Selection Sort +# Code is contributed by: Italo Vinicius. +# +# Selection sort is an Sorting Algorithm which takes compelxity: O(n²) + +# Function to do selection sort +def selectionSort(arr): + + # Traverse through all array elements + for i in range(len(arr)): + + # Find the minimum element in remaining + # unsorted array + min_idx = i + for j in range(i+1, len(arr)): + if arr[min_idx] > arr[j]: + min_idx = j + + # Swap the found minimum element with + # the first element + arr[i], arr[min_idx] = arr[min_idx], arr[i] + +if __name__ == "__main__": + arr = list(map(int,input().split())) + selectionSort(arr) + + print(' '.join(str(x) for x in arr)) \ No newline at end of file