16.0k views
4 votes
Module insertSort (Integer Ref array, Integer arraySize) Declare Integer unsortedValue Declare Integer index Declare Integer scan For index = 1 To arraySize - 1 Set unsortedValue = array[index] Set scan = index While scan > 0 AND array[scan -1] > unsortedValue Set array [scan] = array [scan -1] Set scan = scan -1 End while Set array[scan] = unsortedValue End For End Module?

User Josh Adell
by
7.4k points

1 Answer

6 votes

Final answer:

The student's question is about the insertion sort algorithm used in computer science for sorting arrays. It uses a loop to place the current value in its correct sorted position by shifting larger elements up.

Step-by-step explanation:

The question pertains to the insertion sort algorithm, a fundamental algorithm in computer science for sorting arrays. The provided code piece reflects the pseudo-code for insertion sort. The insertion sort algorithm works by dividing the input array into a 'sorted' and 'unsorted' part. Values from the unsorted part are picked and placed at the correct position in the sorted part.

  1. The 'For' loop starts with the second element of the array (since the first element is considered sorted), setting unsortedValue to the current value and scan to the current position.
  2. A 'While' loop then checks if there are any elements in the sorted part greater than unsortedValue. If so, it continues to shift these elements one position up to make space for unsortedValue.
  3. When the correct position is found (or scan reaches the beginning of the array), unsortedValue is inserted.
  4. This process repeats until the array is completely sorted.

The algorithm reduces the number of moves by only shifting elements, rather than swapping, which makes it efficient for nearly sorted arrays or small arrays.

User Michael Wagner
by
6.7k points