Insertion Sort DATA STRUCTURE & ALGORITHM In python
Вставка
- Опубліковано 16 вер 2024
- Let's break down each line of the `insertion sort` function and the example usage:
python
def insertion sort(arr):
Traverse through 1 to len(arr)
for i in range(1, len(arr)):
```
- This line defines a function `insertion sort` that takes a list `arr` as an argument. The function implements the Insertion Sort algorithm. The `for` loop starts from index 1 to the length of the array.
key = arr[i]
- Inside the loop, it assigns the value at index `i` in the array to the variable `key`. This value will be compared and moved to its correct position in the sorted part of the array.
Move elements of arr[0.i-1] that are greater than key
to one position ahead of their current position
j = i - 1
while j = 0 and key arr[j]:
arr[j + 1] = arr[j]
j -= 1
- This part of the code is responsible for moving the elements that are greater than the `key` to one position ahead of their current position. It uses a `while` loop to iterate through the sorted part of the array (from index 0 to `i-1`) and shifts elements to the right until it finds the correct position for the `key`.
Place the key in its correct position
arr[j + 1] = key
- Once the correct position for the `key` is found (where `key` is greater than the element at index `j`), it places the `key` in its correct position in the sorted part of the array.
Example usage:
my_list = [64, 34, 25, 12, 22, 11, 90]
print ("Original list:", my_list)
insertion_sort(my_list)
print ("Sorted list:", my_list)
- This part demonstrates the usage of the `insertion_sort` function. It initializes a list `my_list`, prints the original list, calls the `insertion_sort` function to sort the list in place, and then prints the sorted list. The sorted list is obtained using the Insertion Sort algorithm.