Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

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

Writer Matthew Harrington

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.

5

24 Answers

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)

#Added parenthesis

5
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]
1

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.

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

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))
def bubble_sort(seq): """Inefficiently sort the mutable sequence (list) in place. seq MUST BE A MUTABLE SEQUENCE. As with list.sort() and random.shuffle this does NOT return """ changed = True while changed: changed = False for i in xrange(len(seq) - 1): if seq[i] > seq[i+1]: seq[i], seq[i+1] = seq[i+1], seq[i] changed = True return None
if __name__ == "__main__": """Sample usage and simple test suite""" from random import shuffle testset = range(100) testcase = testset[:] # make a copy shuffle(testcase) assert testcase != testset # we've shuffled it bubble_sort(testcase) assert testcase == testset # we've unshuffled it back into a copy

From :

4

Here is a not very efficient sorting algorithm :)

>>> data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
>>> from itertools import permutations
>>> for p in permutations(data_list):
... if all(i<=j for i,j in zip(p,p[1:])):
... print p
... break
...
(-23, -6, -5, 0, 5, 23, 23, 67)
2

try sorting list , char have the ascii code, the same can be used for sorting the list of char.

aw=[1,2,2,1,1,3,5,342,345,56,2,35,436,6,576,54,76,47,658,8758,87,878]
for i in range(aw.__len__()): for j in range(aw.__len__()): if aw[i] < aw[j] :aw[i],aw[j]=aw[j],aw[i]
data = [3, 1, 5, 2, 4]
n = len(data) for i in range(n): for j in range(1,n): if data[j-1] > data[j]: (data[j-1], data[j]) = (data[j], data[j-1]) print(data)
1
# Your current setup
data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
new_list = []
# Sort function
for i in data_list: new_list = [ x for x in new_list if i > x ] + [i] + [ x for x in new_list if i <= x ]
2

My method-

s = [-5, -23, 5, 0, 23, -6, 23, 67]
nl = []
for i in range(len(s)): a = min(s) nl.append(a) s.remove(a)
print nl
2

Here's a more readable example of an in-place Insertion sort algorithm.

a = [3, 1, 5, 2, 4]
for i in a[1:]: j = a.index(i) while j > 0 and a[j-1] > a[j]: a[j], a[j-1] = a[j-1], a[j] j = j - 1
def my_sort(lst): a = [] for i in range(len(lst)): a.append(min(lst)) lst.remove(min(lst)) return a
def my_revers_sort(lst):#in revers!!!!! a = [] for i in range(len(lst)): a.append(max(lst)) lst.remove(max(lst)) return a

You could do it easily by using min() function

`def asc(a): b=[] l=len(a) for i in range(l): x=min(a) b.append(x) a.remove(x) return b print asc([2,5,8,7,44,54,23])`

Solution

mylist = [1, 6, 7, 8, 1, 10, 15, 9]
print(mylist)
n = len(mylist)
for i in range(n): for j in range(1, n-i): if mylist[j-1] > mylist[j]: (mylist[j-1], mylist[j]) = (mylist[j], mylist[j-1])
print(mylist)
n = int(input("Input list lenght: "))
lista = []
for i in range (1,n+1): print ("A[",i,"]=") ele = int(input()) lista.append(ele)
print("The list is: ",lista)
invers = True
while invers == True: invers = False for i in range (n-1): if lista[i]>lista[i+1]: c=lista[i+1] lista[i+1]=lista[i] lista[i]=c invers = True
print("The sorted list is: ",lista)

Swapping the values from 1st position to till the end of the list, this code loops for ( n*n-1)/2 times. Each time it pushes the greater value to the greater index starting from Zero index.

list2 = [40,-5,10,2,0,-4,-10]
for l in range(len(list2)): for k in range(l+1,len(list2)): if list2[k] < list2[l]: list2[k] , list2[l] = list2[l], list2[k]
print(list2)
0

Since complexity doesn’t matter, I present to you...BogoSort:

from random import shuffle
def is_sorted(ls): for idx in range(len(ls)-1): if x[idx] > x[idx + 1]: return False return True
def sort(ls): while not is_sorted(ls): shuffle(ls) return ls
ls = list(range(5))
shuffle(ls)
print( "Original: ", ls
)
print( "Sorted: ", sorted(ls)
)

This is the unsorted list and we want is 1234567

list = [3,1,2,5,4,7,6]
def sort(list): for i in range(len(list)-1): if list[i] > list[i+1]: a = list[i] list[i] = list[i+1] list[i+1] = a print(list)
sort(list)

simplest in simplest method to sort a array. Im using currently bubble sorting that is: it checks first 2 location and moves the smallest number to left so on. "-n"in loop is to avoid the indentation error you will understand it by doing it so.

You can used iterative approach one by one comparing along with recursive function. The result in ascending order if you want descending order then change the condition from if l[i]>l[i+1] to if l[i]<l[i+1]:

l=[2,1,3,4,3,2,1,2]
list_len=len(l)
def fun(l): for i in range(list_len): if i<list_len-1: if l[i]>l[i+1]: l[i],l[i+1]=l[i+1],l[i] fun(l) return l
print(fun(l))
for i in range (0, len(unsorted_list)): for j in range (i, len(unsorted_list)): if unsorted_list[i]> unsorted_list[j]: unsorted_list[i], unsorted_list[j] = unsorted_list[j], unsorted_list[i]
print("Sorted list: ", unsorted_list)

output is: Sorted list: [0, 5, 9, 10, 11, 20, 100, 100]

Time complexity is Quadratic time – O (n^2)

Use this with for loop

 arr = [1, 5, 0, 0, 9, 10, 9, 3, 2, 3, 5,10] new_arr = [] for index in range(len(arr)): index = len(new_arr) - index max_val = arr[index] for val in arr[index+1:]: if val >= max_val: max_val = val new_arr.append(max_val) arr.remove(max_val) print(new_arr)

Use this with while loop

 arr = [1, 5, 0, 0, 9, 10, 9, 3, 2, 3, 5,10] new_arr = [] while arr: max_val = arr[0] for x in arr: if x >= max_val: max_val = x new_arr.append(max_val) arr.remove(max_val) print(new_arr)

With function,for ASC use reverse = 1 and -1 for DESC

 def custom_sorting(numbers, new_list, reverse=-1): for i in range(len(numbers)): first_num = numbers[0] for num in numbers: if num < first_num and reverse < 0: first_num = num if num > first_num and reverse > 0: first_num = num numbers.remove(first_num) new_list.append(first_num) if __name__ == "__main__": data = [5, 4, 2, 8, 70, 0, 0, 96, 5] newlist = [] custom_sorting(data, newlist, reverse=1) print(newlist)

How do I keep looping through until the len(new_list) = len(data_list)

while len(new_list) != len(data_list): # ...

Maybe like this?

And no, it’s not necessary to create a new list; most sorting algorithms work by changing the list in place.

What you probably trying to do is Selection sort with a separate list. See the Wikipedia article for more information about that sorting algorithm and you’ll see how it works with a single list, and how efficient it is (spoiler: it isn’t).

4
def getIndexOfMaximum(list1): index = 0 emptyList = [] value = list1[0] c = 0 while (c == 0): for cell in list1: index += 1 if (cell >= value): value = cell hold = index -1 if (len(list1) == index): emptyList += [value] del list1[hold] index = 0 value = 0 if (len(list1) == 1): newList = emptyList + list1 del list1[index] c = 1 return newList
print(getIndexOfMaximum([2,5,8,7,44,54,23]))
#TRY THIS!!!
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy