0

Hey all so im a bit new to python and I need to create a select sort function without any for or whiles but this is all i have so far any help would be greatly appreciated.

def selection_sort(list):
   l=list[:]                  
   sorted=[]                  
   while len(l):              
       lowest=l[0]            
       for x in l:            
           if x<lowest:      
               lowest=x
       sorted.append(lowest) 
       l.remove(lowest)       
   return sorted

Edited by brianmitchell: n/a

6
Contributors
10
Replies
13
Views
6 Years
Discussion Span
Last Post by seanbp
0

You are saying that you don't want to use loops(while, for), then why are you using it yourself??

If you don't use loops, it would make the code large, and dependent to the size of the items you are trying to sort.

0

I want to use list comprehension instead of loops

while len(l):              
       lowest=l[0]            
       for x in l:
0

If you want to do a selection sort without any for/while, you have to do a recursive function.

List comprehension does contain a for loop.

Hopefully helpful hint:
A selection sort of a list of numbers is pretty simple. You start
with two lists, let's call the original unsorted list the start_list
and you have another list call it the end_list which is empty at
the start.

If you want to sort ascending (lowest value first) you get the lowest
value of start_list using lowest = min(start_list) and append it to
the end_list with end_list.append(lowest). Now remove this value from
the start_list with start_list.remove(lowest) and repeat until the
start_list is empty and return the end_list with the sorted values.

Edited by vegaseat: n/a

0

Here's quicksort in Python:

def quicksort(array):
    if array == []: return []
    pivot = array.pop(0)
    low = quicksort([i for i in array if i < pivot])
    high = quicksort([i for i in array if i >= pivot])
    return low + [pivot] + high

print (quicksort([4, 2, 6, 9, 1, 3, 0]))
Votes + Comments
OP asks for selection sort, not quicksort!
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.