Welcome, guest | Sign In | My Account | Store | Cart

This is a variant of selection sort without using for-statements. Do you like it? :-)

Python, 17 lines
 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17``` ```selection_sort = lambda sort_list: reduce( lambda my_list, i: ( lambda max_value=reduce( lambda a, b: b if b > a else a, my_list ): [ my_list.remove(max_value), my_list.append(max_value) ] and my_list )(), range(len(sort_list)), [[], sort_list] ) test_list = [ 5, 1, 7, 0, -3, -10, 10, -6, 1, 0, 2, 4, -2, 6, 5, 8, 2] print test_list print selection_sort(test_list) ```

#### 1 comment Matteo Dell'Amico 13 years, 12 months ago

This is simpler and doesn't use the imperative constructs list.remove and list.append:

``````def selsort(l):
if not l: return []
idx, v = min(enumerate(l), key=operator.itemgetter(1))
return [v] + selsort(l[:idx] + l[idx + 1:])
``````

...or was it the challenge to have it all in a single expression?

``````selsort2 = (lambda l: [] if not l else
(lambda (idx, v): [v] + selsort(l[:idx] + l[idx + 1:]))
(min(enumerate(l), key=lambda(i, x): x)))
`````` Created by pavel on Tue, 29 Sep 2009 (MIT)

### Required Modules

• (none specified)