Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

sorting - python: order a list of numbers without built-in sort, min, max function

If I have a list that varies in length each time and I want to sort it from lowest to highest, how would I do that?

If I have: [-5, -23, 5, 0, 23, -6, 23, 67]

I want: [-23, -6, -5, 0, 5, 23, 23, 67]

I start with this:

data_list = [-5, -23, 5, 0, 23, -6, 23, 67]

new_list = []

minimum = data_list[0]  # arbitrary number in list 

for x in data_list: 
  if x < minimum:
    minimum = value
    new_list.append(i)

BUT this only goes through once and I get:

new_list = [-23] 

This is where I get stuck.

How do I keep looping through until the len(new_list) = len(data_list) (i.e. all the numbers are in the new list) with everything sorted without using the built in max, min, sort functions? I'm not sure if it's necessary to create a new list either.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I guess you are trying to do something like this:

data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
new_list = []

while data_list:
    minimum = data_list[0]  # arbitrary number in list 
    for x in data_list: 
        if x < minimum:
            minimum = x
    new_list.append(minimum)
    data_list.remove(minimum)    

print new_list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...