Lecture 2/13 - CSC1302

Selection Sort

  • Definition: Selection sort is an in-place comparison sorting algorithm that divides the input list into two parts: a sorted and an unsorted region. In each iteration, the smallest (or largest) element from the unsorted region is selected and moved to the sorted region.

Basic Procedure

  • Array Example: To sort an array in ascending order:

    • Start at the first index.

    • Identify the minimum element from the remaining unsorted portion of the array.

    • If the current item (e.g., 4) is greater than the minimum item found (e.g., 2):

      • Swap their values.

  • Final Steps: Continue this process until all elements are sorted, leading to an array that looks like [2, 4, 12, 23].

Steps to Implement Selection Sort

  1. Initialization: Use a for loop to iterate over each element in the array, marking the current index.

  2. Finding Minimum: Within each iteration, determine the minimum from the unsorted elements.

  3. Swapping Elements: If the current element is not in the right order, swap them.

  4. Repeat: Move to the next position and repeat the process until the entire array is sorted.

Example with Cards

  • Scenario:

    • Imagine holding a sorted hand of cards in one hand (4, 5, 7, 9) and an unsorted hand in the other.

  • Process: Choose a card from the unsorted hand:

    • If the card needs a place in the sorted hand, create space and insert the card into the proper position by making comparisons of its value.

Code Implementation

  • Loops:

    • For Loop: Runs for n - 1 iterations where n is the length of the array. It defines how many elements need to be sorted.

    • While Loop: Used to shift elements in the sorted portion to make space for the selected element from the unsorted portion. It will continue until the correct position is found.

Algorithm Efficiency

  • Performance Analysis: The initial three sorting algorithms discussed show less efficiency compared to more advanced algorithms (e.g. quicksort or mergesort). They will continue to be presented for educational purposes despite being less efficient.

Additional Questions

  • Example to Consider:

    • Slicing a string or array such as array[1:-1] will yield certain outputs based on the index specification.

  • Emphasize the importance of understanding what the outer for loop controls in terms of indexing through the elements in both sorting algorithms and string manipulation.

robot