From 4a0fe93b07ee5ad04f0ce232863d5662708f13f6 Mon Sep 17 00:00:00 2001 From: Samic18 <81183716+Samic18@users.noreply.github.com> Date: Wed, 12 Oct 2022 00:30:35 +0530 Subject: [PATCH] Create InsertionSort.py --- InsertionSort,py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 InsertionSort,py diff --git a/InsertionSort,py b/InsertionSort,py new file mode 100644 index 00000000..095f8e2d --- /dev/null +++ b/InsertionSort,py @@ -0,0 +1,27 @@ +# Insertion Sort in python +# Time Complexity +# Best O(n) +# Worst O(n^2) +# Average O(n^2) +# Space Complexity O(1) + +def insertionSort(array): + + for step in range(1, len(array)): + key = array[step] + j = step - 1 + + # Compare key with each element on the left of it until an element smaller than it is found + # For descending order, change keyarray[j]. + while j >= 0 and key < array[j]: + array[j + 1] = array[j] + j = j - 1 + + # Place key at after the element just smaller than it. + array[j + 1] = key + + +data = [19, 14, 1, 44, 23] +insertionSort(data) +print('Sorted Array in Ascending Order:') +print(data)