From 62992f81081b43699cce885c97937e120452864b Mon Sep 17 00:00:00 2001 From: Shivity2003 <91420995+Shivity2003@users.noreply.github.com> Date: Thu, 5 Oct 2023 18:56:03 +0530 Subject: [PATCH] Create insertion sort --- insertion sort | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 insertion sort diff --git a/insertion sort b/insertion sort new file mode 100644 index 00000000..96db6e3d --- /dev/null +++ b/insertion sort @@ -0,0 +1,25 @@ +# Creating a function for insertion sort algorithm +def insertion_sort(list1): + + # Outer loop to traverse on len(list1) + for i in range(1, len(list1)): + + a = list1[i] + + # Move elements of list1[0 to i-1], + # which are greater to one position + # ahead of their current position + j = i - 1 + + while j >= 0 and a < list1[j]: + list1[j + 1] = list1[j] + j -= 1 + + list1[j + 1] = a + + return list1 + +# Driver code +list1 = [ 7, 2, 1, 6 ] +print("The unsorted list is:", list1) +print("The sorted new list is:", insertion_sort(list1))