Lab 9 - Quadratic Sorting Algorithms

The purpose of this lab is implement the two common quadratic sorting algorithms: selection sort and insertion sort.

We will start this lab with a 30-45 minute lecture on what these two sorting algorithms are actually doing to sort the values. Then you will implement the two sorting algorithms and see that they do indeed sort arrays. These algorithms are quadratic because they use two nested loops, with each loop in the worst case going through nearly all of the items in the array. So each loop is O(n) and the nested loops are O(n2).

You will implement the pseudocode for selection sort and for insertion sort. Use lab9.cpp for your main function. This sets up two arrays that are copies of one another and then calls the two sorting algorithms. If they are both working correctly, you will see the sorted values printed out twice. You can alter the input loop to read from a file if you wish, but be sure to make two copies of the data (two arrays with the same data) so you can pass each algorithm their own copy to sort.

The pseudocode for selection sort is:

Given: array of elements, size of the array
Returns: nothing, sorts values in array

for i = 0 to i < size - 1
  set min to array[i+1]  (scan rest of the array for its minimum)
  set minPos to i+1
  for j = i+2 to j < size
    if array[j] < min
      set min to array[j]
      set minPos to j
    end-if
  end-for
  if min < array[i]   (swap if rest of array has a smaller value than array[i])
    set array[minPos] to array[i]
    set array[i] to min
  end-if
end-for
The pseudocode for insertion sort is:
Given: array of elements, size of the array
Returns: nothing, sorts values in array

for pos = 1 to pos < size
  set value to array[pos]
  set j to pos
  (scan sorted subset for correct position, also shift to make hole for array[pos])
  while value < array[j-1]
    set array[j] to array[j-1]   (shift the larger element up one slot)
    decrement j
    if j equals 0                (stop when we reach the start of the array)
      break out of loop
    end-if
  end-while
  set array[j] to value          (copy into hole made by above loop)
end-for
Email your completed lab9.cpp to Terry.