Search code examples
pythonrandombubble-sort

random generating numbers in Bubble Sort


Here is my question I would like to not use numbers that I use but rather that I can put in random numbers ranging from 0 to 50 and then the list can use bubble method to sort it but I can understand how I can use the randomly generated numbers in here

def bubbleSort(array):

  for i in range(len(array)):
    data = [8, 45, 0, 11, 6]
    swapped = False

    for j in range(0, len(array) - i - 1):

      if array[j] > array[j + 1]:

        # swapping occurs if elements
        # are not in the intended order
        temp = array[j]
        array[j] = array[j+1]
        array[j+1] = temp

        swapped = True

    if not swapped:
      break

Solution

  • You must call your function with the list you want to sort, i.e. with the function:

    def bubble_sort(lst):
        n = len(lst)
        for i in range(n - 1):
            swapped = False
    
            for j in range(0, n - i - 1):
                if lst[j] > lst[j + 1]:
                    swapped = True
                    lst[j], lst[j+1] = lst[j+1], lst[j]
    
            if not swapped:
                return
    

    You'll call it like this:

    data = [8, 45, 0, 11, 6]
    bubble_sort(data)
    print(data)   # should now be sorted
    

    (bubble sort, sorts the list in-place)