From 301e128e019a8c15cdd6b5decc045286943f6be1 Mon Sep 17 00:00:00 2001 From: sumant7 <91867296+sumant7@users.noreply.github.com> Date: Fri, 6 Oct 2023 22:28:23 +0530 Subject: [PATCH] Added Insertion Sort --- Sorting/insertionsort.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Sorting/insertionsort.py diff --git a/Sorting/insertionsort.py b/Sorting/insertionsort.py new file mode 100644 index 00000000..be0fd9fb --- /dev/null +++ b/Sorting/insertionsort.py @@ -0,0 +1,18 @@ +def insertionSort(arr): + n = len(arr) # Get the length of the array + + if n <= 1: + return # If the array has 0 or 1 element, it is already sorted, so return + + for i in range(1, n): # Iterate over the array starting from the second element + key = arr[i] # Store the current element as the key to be inserted in the right position + j = i-1 + while j >= 0 and key < arr[j]: # Move elements greater than key one position ahead + arr[j+1] = arr[j] # Shift elements to the right + j -= 1 + arr[j+1] = key # Insert the key in the correct position + +# Sorting the array [12, 11, 13, 5, 6] using insertionSort +arr = [12, 11, 13, 5, 6] +insertionSort(arr) +print(arr)