Advertisement
Talilo

Insertion_sort.py

Mar 16th, 2023 (edited)
548
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.67 KB | None | 0 0
  1. # Insertion sort in Python
  2. #https://www.programiz.com/dsa/insertion-sort
  3.  
  4. def insertionSort(array):
  5.  
  6.     for step in range(1, len(array)):
  7.         key = array[step]
  8.         j = step - 1
  9.        
  10.         # Compare key with each element on the left of it until an element smaller than it is found
  11.         # For descending order, change key<array[j] to key>array[j].        
  12.         while j >= 0 and key < array[j]:
  13.             array[j + 1] = array[j]
  14.             j = j - 1
  15.        
  16.         # Place key at after the element just smaller than it.
  17.         array[j + 1] = key
  18.  
  19.  
  20. data = [9, 5, 1, 4, 3]
  21. insertionSort(data)
  22. print('Sorted Array in Ascending Order:')
  23. print(data)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement