kostis tzimoulias
kostis tzimoulias

Reputation: 13

Selection_sort (python)

I came across this code on selection sort algorithm:

ls = [2, 5, 1, -9, 10, 13, 7, 2]


def selection_sort(ls):
      for i in range(len(ls)):
         imin = min(range(i,len(ls)), key = lambda x: ls[x])
         ls[i], ls[imin] = ls[imin], ls[i]

I know the typical selection_sort with the if block, but this one is hard to understand. I tried to print imin with all possible i's and the result was 33337777 which doesn't make sense to me. I think my problem is that I don't know how this specific key works. Does anyone have any insight on this?

Upvotes: 0

Views: 57

Answers (1)

Sidharth Mudgil
Sidharth Mudgil

Reputation: 1461

function declaration

The statement is the function definition, Which takes one argument i.e. list

def selection_sort(ls):

Loop Initialization

A for-loop is defined that will iterate the list from i = 0 to the len(ls).

for i in range(len(ls)):

Main Logic

Inside the for-loop, there are 2 statements

imin = min(range(i,len(ls)), key = lambda x: ls[x])

The above code uses python's min function taking 2 arguments, an iterator and a function to find the minimum value from the list starting from index i to len(ls) and return the item's index using the lambda function passed as the second argument.

ls[i], ls[imin] = ls[imin], ls[i]

The above code is responsible for swapping the minimum item with the item at the index i of the list.

Upvotes: 0

Related Questions