BecauseImBatmanFilms
BecauseImBatmanFilms

Reputation: 19

Selection Sort Problems

I'm attempting to create a simple selection sort program in python without using any built in functions. My problem right now is my code is only sorting the first digit of the list. What's wrong?

Here's my sort

  def selectionsort(list1):
    for x in range(len(list1)):
      tiniest = minimum(list1)
      swap(tiniest,x,list1)
  return(list1)

Here's the minimum and swap functions I'm using

    def swap(index1,index2,list1):
       TheList = list1 
       temp = TheList[index1]
       TheList[index1] = TheList[index2]
       TheList[index2] = temp
       return(TheList)
    def minimum(list1):
       small = list1[0] 
       for i in list1:
          if i < small:
          small = i
       return small

An example of output List = [3,2,1,0]

Output = [0,2,1,3]

Upvotes: 0

Views: 142

Answers (2)

user2390182
user2390182

Reputation: 73450

Some simplification will make it more readable/comprehensible:

def swap(lst, i1, i2):
  lst[i1], lst[i2] = lst[i2], lst[i1]  # easy-swapping by multi assignment 

def minimum(lst, s):  # s: start index
  min_val, min_index = lst[s], s
  for i in range(s+1, len(lst)):
    if lst[i] < min_val:
      min_val, min_index = lst[i], i
  return min_index  # return index of minimum, not minimum itself

def selection_sort(lst):
  for i in range(len(lst)): 
    swap(lst, i, minimum(lst, i))  
    # find min index starting from current and swap with current

Upvotes: 1

Coolness
Coolness

Reputation: 1982

It seems minimum returns the value of the smallest element in list1, but your swap expects an index instead. Try making minimum return the index instead of the value of the smallest element.

Upvotes: 0

Related Questions