4. Insertion Sort • The idea with an insertion sort is that a sorted region grows one item at a time, by inserting an item into its correct position within the sorted region. • As done in Part 1, fill an array with random numbers. • Write a function that inserts an item into a sorted region of an array. Pass the function the index of the item to be inserted (i.e. the index of the first item in the unsorted region). Insert that item by shifting items over one position, until you have found the correct location to insert the item. • E.g. if given a = [2 5 8 9 6 3 7] and the index 4, a[4] should be inserted into the sorted portion, giving [2 5 6 8 9 3 7] • Write a second function that calls the first function repeatedly, until the entire array is sorted. (Each time the first function is called, it will insert an item into a larger sorted region.)
4. Insertion Sort
• The idea with an insertion sort is that a sorted region grows one item at a
time, by inserting an item into its correct position within the sorted region.
• As done in Part 1, fill an array with random numbers.
• Write a function that inserts an item into a sorted region of an array. Pass
the function the index of the item to be inserted (i.e. the index of the first
item in the unsorted region). Insert that item by shifting items over one
position, until you have found the correct location to insert the item.
• E.g. if given a = [2 5 8 9 6 3 7] and the index 4, a[4] should be inserted into the
sorted portion, giving [2 5 6 8 9 3 7]
• Write a second function that calls the first function repeatedly, until the
entire array is sorted. (Each time the first function is called, it will insert an
item into a larger sorted region.)
Step by step
Solved in 2 steps with 1 images