1

I am trying to sort 4 numbers and do it without using any built-in functions. Here is what I have which works in some cases.

#sort numbers

def sort_n(w, x, y, z):
    list = [w, x, y, z]
    while list[3] < list[2]:

        if list[0] > list[1]:
            list[0], list[1] = list[1], list[0]

        if list[1] > list[2]:
            list[1], list[2] = list[2], list[1]

        if list[2] > list[3]:
            list[2], list[3] = list[3], list[2]
    while list[1] < list[2]:

        if list[0] > list[1]:
            list[0], list[1] = list[1], list[0]

        if list[1] > list[2]:
            list[1], list[2] = list[2], list[1]

        if list[2] > list[3]:
            list[2], list[3] = list[3], list[2]

    while list[1] < list[0]:

        if list[0] > list[1]:
            list[0], list[1] = list[1], list[0]

        if list[1] > list[2]:
            list[1], list[2] = list[2], list[1]

        if list[2] > list[3]:
            list[2], list[3] = list[3], list[2]

    print list


sort_n(10, 1, 2, 3)
user2357112
  • 260,549
  • 28
  • 431
  • 505
omrigildor
  • 11
  • 2

3 Answers3

1
def bubble_sort(a_list):
    changed = True
    while changed:
        changed = False
        for i in range(len(a_list)-1):
            if a_list[i] > a_list[i+1]:
                 changed = True
                 a_list[i],a_list[i+1] = a_list[i+1],a_list[i]
    return a_list

I think anyway ...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
1

Inplace insertion sort

def isort(a, f):
    for i in range(0, len(a)):
        for j in range(0, i):
            if f(a[i], a[j]):
                a[j], a[i] = a[i], a[j]
    return a

Then you can use it like so

>>> isort([2,9,8,3], lambda x, y: x < y) # Ascending order
[2, 3, 8, 9]
>>> isort([2,9,8,3], lambda x, y: x > y) # Descending order
[9, 8, 3, 2]

However it does use len and range which are builtins...

Ford
  • 2,559
  • 1
  • 22
  • 27
0

you may be looking for the optimal sorting network for 4 numbers.

there are more details (in c) at Standard sorting networks for small values of n and more basic introduction here.

unfortunately i can't find a python implementation for the n=4 case. but the question linked above contains:

 - 4-input: 3 networks

[[1 2][3 4][1 3][2 4][2 3]]
[[1 3][2 4][1 2][3 4][2 3]]
[[1 4][2 3][1 2][3 4][2 3]]

and if i understand correctly, you can pick any line and then do the comparisons described there. so taking the first line:

if list[1] > list[2]: list[1], list[2] = list[2], list[1]
if list[3] > list[4]: list[3], list[4] = list[4], list[3]
if list[1] > list[3]: list[1], list[3] = list[3], list[1]
if list[2] > list[4]: list[2], list[4] = list[4], list[2]
if list[2] > list[3]: list[2], list[3] = list[3], list[2]

but i really need to dash and haven't tested that...

Community
  • 1
  • 1
andrew cooke
  • 45,717
  • 10
  • 93
  • 143