Home > other >  Bubble Sort Python sorting only once
Bubble Sort Python sorting only once

Time:05-25

Can anyone help me in identifying the error in this program for bubble sort?

def bsort(a):
    for i in range (0, len(a)-1):
        for j in range(i):
            if a[j]> a[j 1]:
                temp = a[j]
                a[j] = a[j 1]
                a[j 1] = temp

num = [1,2,6,5,7,2,5,9]
bsort(num)
print(num)

It sorts the list only once.

CodePudding user response:

Change the range in the outer loop:

for i in range (0, len(a)):

CodePudding user response:

Minor issues in for loop.

def bsort(a):
    for i in range (0, len(a)-1):
        for j in range(len(a)-2): ## updated here
            if a[j]> a[j 1]:
                temp = a[j]
                a[j] = a[j 1]
                a[j 1] = temp

num = [1,2,6,5,7,2,5,9]
bsort(num)
print(num)

Output is [1, 2, 2, 5, 5, 6, 7, 9]

CodePudding user response:

there is a mistake in your loop, you seem to swap the wrong indexes.

    def bsort(a):
        for i in range (0, len(a)-1):
            for j in range(i):
                if a[j]> a[j 1]:
                    temp = a[j]
                    print(f'swapping {a[j]} with {a[j 1]}')
                    print(f'swapping {a[j 1]} with {temp}')
                    a[j] = a[j 1]
                    a[j 1] = temp
    
    num = [1,2,6,5,7,2,5,9]
    
    bsort(num)
    print(num)
    

swapping 6 with 5
swapping 5 with 6
swapping 7 with 2
swapping 2 with 7
swapping 6 with 2
swapping 2 with 6
swapping 7 with 5
swapping 5 with 7
[1, 2, 5, 2, 6, 5, 7, 9]

Try this instead

    def bubble_sort(arr):
        for itm in arr:
            for idx in range(len(arr)-1):
                if arr[idx] > arr[idx 1]:
                    print(f'swapping {arr[idx]} with {arr[idx 1]}')
                    arr[idx],arr[idx 1]=arr[idx 1],arr[idx]
        return arr
    print(bubble_sort(num))

swapping 5 with 2
swapping 6 with 5
[1, 2, 2, 5, 5, 6, 7, 9]

  • Related