Photo AI
Question 3
An insertion sort is one type of sorting algorithm. A student has written a pseudocode algorithm to perform an insertion sort on a 1D array names. names = ["Kareem... show full transcript
Step 1
Answer
The variable temp
is used as a temporary storage location during the swapping process in the insertion sort algorithm. When an element at position pos
is less than the element at position pos - 1
, the value of names[pos]
is stored in temp
. This allows the algorithm to safely overwrite names[pos]
with the value from names[pos - 1]
before the original value is lost. After this, the value in temp
is then assigned to names[pos - 1]
, completing the swap.
Step 2
Answer
One key difference between an insertion sort and a bubble sort is the approach to sorting. The insertion sort builds a sorted section of the array one element at a time by comparing and inserting each new element into its correct position. In contrast, the bubble sort repeatedly steps through the array, compares adjacent elements, and swaps them if they are in the wrong order, effectively 'bubbling' the largest unsorted element to its correct position with each iteration.
Report Improved Results
Recommend to friends
Students Supported
Questions answered