Computer Science – Algorithm design and problem-solving | e-Consult
Algorithm design and problem-solving (1 questions)
Login to see all questions.
Click on a question to view the answer
Errors in the Algorithm:
- Incorrect Initialisation: The algorithm assumes the first number is the smallest, which is incorrect for sorting in ascending order. It should assume the first number is the first element to be considered for the smallest value.
- Incorrect Comparison: The algorithm compares the current number with the *smallest number found so far*. This is not correct for selection sort. It should compare the current number with the *smallest number in the unsorted portion of the list*.
- Missing Unsorted Portion: The algorithm doesn't explicitly define the "unsorted portion" of the list. It should iterate through the unsorted portion and find the minimum element within that portion.
Suggested Corrections:
- Initialisation: The algorithm should start by assuming the first element of the list is the smallest and storing it as the initial smallest value.
- Comparison: The algorithm should compare the current number with the smallest value found *within the unsorted portion of the list*. This requires tracking the index of the start and end of the unsorted portion.
- Unsorted Portion: The algorithm needs to explicitly define and manage the unsorted portion of the list. This is typically done by iterating through the list, selecting the minimum element in the unsorted portion, and placing it at the correct position in the sorted portion.
Corrected Algorithm (Pseudocode):
- Let
smallest_indexbe the index of the first element in the list. - For each index
ifromsmallest_indexto the end of the list: - Assume the element at index
iis the smallest. - For each index
jfromsmallest_indextoi: - If the element at index
jis less than the element at indexi: - Swap the elements at indices
jandi. - End For
- End For