Already sorted list

I want to stop my bubble sort function if it is given a list that is already ordered (or already ordered halfway through the bubble sort path)

I defined the bubble sort function as

def swap(values,i,j):
    values[i],values[j]=values[j],values[i]

def bubble(values):
    for i in range (len(values)-1):
        if values[i]>values[i+1]:
            swap(values,i,i+1)

def bubble_sort(values):
    count = 0
    for i in range(len(values)-1):
        count += 1
        bubble(values)
    return count

Here I count how many times I call the bubble function to see how many times a swap is executed. I want to change the code so that if it is given a list that is already sorted, the function bubble_sort()will stop calling the function bubble().

I know that I will have to use a boolean in the bubble function, which returns if any values ​​have been replaced, but I'm not sure how to implement it.

+4
source share
2 answers

, ( off jet) Boolean , True False, , , oposite, , , , , , , . while,

def bubble(values):
    "return true if a swap was made, false otherwise" 
    flag = False
    for i in range(len(values)-1):
        if values[i]>values[i+1]:
            swap(values,i,i+1)
            flag = True
    return flag

def bubble_sort(values):
    count = 0 
    while bubble(values): # while there is a swap...
        count += 1
    return count 

>>> test=[1,9,4,7,2,8,10,5,6,3]
>>> bubble_sort(test)
7
>>> test
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> bubble_sort(test)
0
>>> test
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> 
+1
def swap(values,i,j):
    values[i],values[j]=values[j],values[i]

def bubble(values):
    flag = False
    for i in range (len(values)-1):
        if values[i]>values[i+1]:
            flag = True
            swap(values,i,i+1)
    return flag

def bubble_sort(values):
    count = 0
    for i in range(len(values)-1):
        count += 1
        if(not bubble(values))
            break
    return count
0

Source: https://habr.com/ru/post/1627704/


All Articles