Python insertion sort
时间: 2023-07-02 20:18:19 浏览: 57
Sure, here's an implementation of the insertion sort algorithm in Python:
```python
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
```
To use this function, simply pass in an array of integers:
```python
my_array = [4, 2, 7, 1, 3]
sorted_array = insertion_sort(my_array)
print(sorted_array) # Outputs [1, 2, 3, 4, 7]
```
The insertion sort algorithm works by iterating through each element in the array one by one, and inserting it into its correct position among the already sorted elements. It does this by comparing the current element to each of the previous elements, and swapping them if necessary until the current element is in the correct position.