[python] 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.

This question is related to python sorting for-loop

The answer is


# 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 ]

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

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!!!

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

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]

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])`

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)

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


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 : http://rosettacode.org/wiki/Bubble_Sort#Python


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.


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)

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.


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)

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)

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

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

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)

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

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]

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to sorting

Sort Array of object by object field in Angular 6 Sorting a list with stream.sorted() in Java How to sort dates from Oldest to Newest in Excel? how to sort pandas dataframe from one column Reverse a comparator in Java 8 Find the unique values in a column and then sort them pandas groupby sort within groups pandas groupby sort descending order Efficiently sorting a numpy array in descending order? Swift: Sort array of objects alphabetically

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?