Advertisement
IMustRemainUnknown

Python Insertion Sort

Dec 18th, 2023
518
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | Source Code | 0 0
  1. def my_insertion_sort(arr):
  2.     sort_arr = []
  3.     unsorted_arr = arr.copy()
  4.  
  5.     for i in range(len(arr)):
  6.         sort_arr.append(unsorted_arr.pop(0))
  7.  
  8.         if len(sort_arr) < 1:
  9.             sort_arr.append(unsorted_arr.pop(0))
  10.  
  11.         if len(unsorted_arr) > 0:
  12.             if sort_arr[-1] > unsorted_arr[0]:
  13.                 sort_arr[-1], unsorted_arr[0], = unsorted_arr[0], sort_arr[-1]
  14.  
  15.         for j in range(len(sort_arr)-1, 0, -1):
  16.             if sort_arr[j-1] > sort_arr[j]:
  17.                 sort_arr[j-1], sort_arr[j] = sort_arr[j], sort_arr[j-1]
  18.             else:
  19.                 break
  20.  
  21.     return sort_arr
  22.  
  23.  
  24. myList = [4, 2, 89, 12, 6, 32]
  25. print(my_insertion_sort(myList))
  26.  
  27. myList = [4, 2, 89, 12, 6, 32, 17, 29, 8, 1]
  28. print(my_insertion_sort(myList))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement