fork download
  1. def insertionSort(arr):
  2. n = len(arr) # Get the length of the array
  3.  
  4. if n <= 1:
  5. return # If the array has 0 or 1 element, it is already sorted, so return
  6.  
  7. for i in range(1, n): # Iterate over the array starting from the second element
  8. key = arr[i] # Store the current element as the key to be inserted in the right position
  9. j = i-1
  10. while j >= 0 and key < arr[j]: # Move elements greater than key one position ahead
  11. arr[j+1] = arr[j] # Shift elements to the right
  12. j -= 1
  13. arr[j+1] = key # Insert the key in the correct position
  14.  
  15. # Sorting the array [12, 11, 13, 5, 6] using insertionSort
  16. arr = [12, 11, 13, 5, 6]
  17. insertionSort(arr)
  18. print(arr)
Success #stdin #stdout 0.03s 9264KB
stdin
Standard input is empty
stdout
[5, 6, 11, 12, 13]