简体   繁体   中英

Sorting algorithm doesn't work

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 .

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]

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM