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:
JavaScript
x
11
11
1
data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
2
3
new_list = []
4
5
minimum = data_list[0] # arbitrary number in list
6
7
for x in data_list:
8
if x < minimum:
9
minimum = value
10
new_list.append(i)
11
BUT this only goes through once and I get:
JavaScript
1
2
1
new_list = [-23]
2
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.
Advertisement
Answer
I guess you are trying to do something like this:
JavaScript
1
13
13
1
data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
2
new_list = []
3
4
while data_list:
5
minimum = data_list[0] # arbitrary number in list
6
for x in data_list:
7
if x < minimum:
8
minimum = x
9
new_list.append(minimum)
10
data_list.remove(minimum)
11
12
print (new_list)
13
#Added parenthesis