S
S
SuperDuperPuper2020-07-27 00:26:25
Python
SuperDuperPuper, 2020-07-27 00:26:25

How to fix my bubble sort algorithm in python?

def buble():
    end = -len(array)

    
    while end!=-1: 
        for el in range(-1,end,-1):
            if array[el]<=array[-1+el]:
                mem = array[el]
                array[el] = array[-1+el]
                array[-1+el] = mem


        end=+1
    print("result is ")
    print(array)



array = [6,7,8,9,5,3,2,1,4,0]
buble()"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Talko, 2020-07-27
@SuperDuperPuper

There is no way to sit down for a laptop (I almost sleep), so I wrote from the phone. I'm not a master of explaining, but I tried to describe each step

def buble(array):
    replaced = True

    for _ in array:
        #Если замен не было - выходим из цикла
        if not replaced: break
        replaced = False
    
        #Проходимся по списку и сравниваем 2 элемента
        for el in range(len(array)-1):

            #Если текущий элемент больше следующего
            if array[el] > array[el+1]:

                #Меняем местами
                array[el], array[el+1] = array[el+1], array[el]
          
                #ставим "флаг" что произошла замена
                replaced = True
    return array

array = [6,7,8,9,5,3,2,1,4,0]
print(buble(array))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question