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, -
Solution 1:
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
Solution 2:
l = [64, 25, 12, 22, 11, 1,2,44,3,122, 23, 34]
for i in range(len(l)):
for j in range(i + 1, len(l)):
if l[i] > l[j]:
l[i], l[j] = l[j], l[i]
print l
Output:
[1, 2, 3, 11, 12, 22, 23, 25, 34, 44, 64, 122]
Solution 3:
Here is something that i have been trying.(Insertion sort- not the best way to sort but does the work)
def sort(list):
for index in range(1,len(list)):
value = list[index]
i = index-1
while i>=0:
if value < list[i]:
list[i+1] = list[i]
list[i] = value
i -= 1
else:
break
Solution 4:
This strictly follows your requirements not to use sort()
, min()
, max()
but also uses Python best practice by not re-inventing the wheel.
data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
import heapq
heapq.heapify(data_list)
new_list = []
while data_list:
new_list.append(heapq.heappop(data_list)))
I suggest having a look in the Python library for heapq.py
to see how it works. Heapsort is quite a fun sorting algorithm as it lets you 'sort' an infinite stream, i.e. you can quickly get at the currently smallest item but also efficiently add new items to the the data to be sorted.
Solution 5:
This works!
def sorting(li):
for i in range(len(li)):
for j in range(len(li)):
if li[i] < li[j]:
li[j],li[i] = li[i],li[j]
return li
listToSort = [22,11,23,1,100,24,3,101,2,4]
print(sorting(listToSort))
Post a Comment for "Python: Order A List Of Numbers Without Built-in Sort, Min, Max Function"