Write a python implementation of insertion sort with example array.
- User
Write a python implementation of insertion sort with example array.
- Assistant
Here's an example implementation of insertion sort in Python, along with a sample array:
def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key return arr # Example array arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] # Call insertion_sort() function print(insertion_sort(arr))This will output:
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]In this example, the insertion_sort() function takes an array as input, then iterates through the array and inserts each element into its correct position within the sorted subarray that precedes it. The key variable stores the current element being sorted, and the j variable is used to iterate through the sorted subarray looking for the correct position to insert the key value. The while loop moves each element of the sorted subarray up one position until the correct insertion point is found, at which point the key value is inserted into the array. The function returns the sorted array.