| 
 | 1 | +"""  | 
 | 2 | +This is pure python implementation of selection sort algorithm  | 
 | 3 | +
  | 
 | 4 | +For doctests run following command:  | 
 | 5 | +python -m doctest -v selection_sort.py  | 
 | 6 | +or  | 
 | 7 | +python3 -m doctest -v selection_sort.py  | 
 | 8 | +"""  | 
 | 9 | +from __future__ import print_function  | 
 | 10 | + | 
 | 11 | +def selection_sort(sortable):  | 
 | 12 | +    """Pure implementation of selection sort algorithm in Python  | 
 | 13 | +
  | 
 | 14 | +    Examples:  | 
 | 15 | +    >>> selection_sort([0, 5, 3, 2, 2])  | 
 | 16 | +    [0, 2, 2, 3, 5]  | 
 | 17 | +
  | 
 | 18 | +    >>> selection_sort([])  | 
 | 19 | +    []  | 
 | 20 | +
  | 
 | 21 | +    >>> selection_sort([-2, -5, -45])  | 
 | 22 | +    [-45, -5, -2]  | 
 | 23 | +
  | 
 | 24 | +    :param sortable: some mutable ordered collection with heterogeneous  | 
 | 25 | +    comparable items inside  | 
 | 26 | +    :return: the same collection ordered by ascending  | 
 | 27 | +    """  | 
 | 28 | +    length = len(sortable)  | 
 | 29 | +    for i in range(length):  | 
 | 30 | +        least = i  | 
 | 31 | +        for k in range(i + 1, length):  | 
 | 32 | +            if sortable[k] < sortable[least]:  | 
 | 33 | +                least = k  | 
 | 34 | +        sortable[least], sortable[i] = (  | 
 | 35 | +            sortable[i], sortable[least]  | 
 | 36 | +        )  | 
 | 37 | +    return sortable  | 
 | 38 | + | 
 | 39 | + | 
 | 40 | +if __name__ == '__main__':  | 
 | 41 | +    import sys  | 
 | 42 | +    # For python 2.x and 3.x compatibility: 3.x has not raw_input builtin  | 
 | 43 | +    # otherwise 2.x's input builtin function is too "smart"  | 
 | 44 | +    if sys.version_info.major < 3:  | 
 | 45 | +        input_function = raw_input  | 
 | 46 | +    else:  | 
 | 47 | +        input_function = input  | 
 | 48 | + | 
 | 49 | +    user_input = input_function('Enter numbers separated by coma:\n')  | 
 | 50 | +    unsorted = [int(item) for item in user_input.split(',')]  | 
 | 51 | +    print(selection_sort(unsorted))  | 
0 commit comments