79528757

Date: 2025-03-23 10:05:34
Score: 0.5
Natty:
Report link

I really made a gross mistake in the python implementation by not first copying the source list, which I am modifying. After adding the copy, the python implementation started to run noticeably slower. Many times slower than the c++ implementation, as expected.

corrected python implementation:

from typing import List
from copy import copy


def find_smallest_element(arr: list) -> int:
    smallest_item = arr[0]
    smallest_idx = 0

    for idx in range(1, len(arr)):
        item = arr[idx]
        if item < smallest_item:
            smallest_item = item
            smallest_idx = idx

    return smallest_idx


def selection_sort(arr: list) -> list:
    sorted_arr = []
    work_arr = copy(arr)  # <-- !!!

    while len(work_arr) != 0:
        smallest_idx = find_smallest_element(work_arr)
        sorted_arr.append(work_arr.pop(smallest_idx))

    return sorted_arr

Thanks, jérôme-richard

updated benchmark result for python:

------------------------------- benchmark: 1 tests ----------------------------------
Name (time in s)                     Min     Max    Mean  StdDev  Median     IQR  
-------------------------------------------------------------------------------------
test_selection_sort_benchmark     1.1131  1.1131  1.1131  0.0000  1.1131  0.0000       
-------------------------------------------------------------------------------------
Reasons:
  • Blacklisted phrase (0.5): Thanks
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Gwinkamp