Home > database >  numpy bubblesort not printing sorted array
numpy bubblesort not printing sorted array

Time:10-21

hi guys umm can you figure out why my bubble sort isnt printing i used numpy aswell

number = int(input('Tell the AI the size of the array ==> '))
            arr = np.random.rand(number)
            def Bubblesort(arr):
                for i in range(len(arr)):
                    for j in range(0, len(arr)):
                        if arr[j] > arr[j   1]:
                            temp = arr[j]
                            arr[j] = arr[j   1]
                            arr[j   1] = temp
                    Bubblesort(arr)
                    print(arr)
        

im srry if i took your time but im a beginner and i really need this prooject to work so please can you help also upvote so more people can see it ok :)

CodePudding user response:

It may not be printing because of the indentation. The call for Bubblesort(arr) is inside the definition of the function. Try moving it to align with the 'def'

    number = int(input('Tell the AI the size of the array ==> '))
    arr = np.random.rand(number)
    def Bubblesort(arr):
        for i in range(len(arr)):
            for j in range(0, len(arr)):
                if arr[j] > arr[j   1]:
                    temp = arr[j]
                    arr[j] = arr[j   1]
                    arr[j   1] = temp
    Bubblesort(arr)
    print(arr)

CodePudding user response:

There were two issues. One, the indentation of Bubblesort(arr) and print(arr) was wrong; it was considered to be within Bubblesort(), meaning that there was never actually any code that called Bubblesort(). So, your program would just end the moment you were done entering in the length of arr.

In addition, once I fixed that issue, your program started giving an error about an array index being out of bounds:

    if arr[j] > arr[j   1]:
IndexError: index 10 is out of bounds for axis 0 with size 10

This is because your code indexes arr[j 1], but it loops up until the length of arr, meaning you're going to index one item past the end of arr. In order to fix it, you just have to loop up until one less than the length of arr. So, I just changed for j in range(0, len(arr)) to for j in range(0, len(arr) - 1).

So, with that fixed, as well as the indentation, your code actually works fine:

import numpy as np

number = int(input('Tell the AI the size of the array ==> '))
arr = np.random.rand(number)


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


Bubblesort(arr)
print(arr)

Output:

Tell the AI the size of the array ==> 10
[0.07201946 0.20971682 0.26190436 0.4245566  0.48094863 0.50693179
 0.52760367 0.82474669 0.86552769 0.90142202]
  • Related