Reputation: 3557
I'm trying to spiff-up my skills and thought I would try to write my own little sorting algorithm:
import random
from random import randint
int_list = []
for i in range(10): #Creates a 10-entry list of randon ints
int_list.append(random.randint(0,10))
print "Unsorted list:\t" + str(int_list)
def sorter(int_list):
for i in range(len(int_list)-1):
while int_list[i] > int_list[i+1]:
temp = int_list[i]
int_list[i] = int_list[i+1]
int_list[i+1] = temp
continue
return int_list
print "\"Sorted\" list:\t" + str(sorter(int_list))
When I run this script it only sorts the first two entries of the list. My understanding of continue
was that it would keep looping through my while loop while the while
statement was True
.
Upvotes: 0
Views: 156
Reputation: 53565
Your while
actually operates like an if
, looks like you're trying to bubble-sort and you're not implementing it correctly (you should keep iterating until the iteration doesn't preform swap even once) - which is why you don't really sort.
Second, the pythonic way to "swap" is not:
temp = int_list[i]
int_list[i] = int_list[i+1]
int_list[i+1] = temp
but rather:
int_list[i], int_list[i+1] = int_list[i+1], int_list[i]
Upvotes: 1
Reputation: 56694
Your return int_list
statement is indented too far - it is within the for
loop, so your function quits at the end of the first iteration.
Also,
int_list = []
for i in range(10): #Creates a 10-entry list of randon ints
int_list.append(random.randint(0,10))
could be reduced to
int_list = [random.randint(0, 10) for i in range(10)]
and the while
is only ever going to run 0 or 1 times (you can just use if
).
Also, it looks like you are just doing the first pass of a bubble sort - it will move the highest value to the end of the list, but will not result in a completely sorted list. You need another for
loop to do this repeatedly ('bubbling up' values).
Upvotes: 0