How to store each step of Bubble Sort into a list of list

Question:

I need to store the image of array after every inner loop so that I can process it later somewhere else.

def bubbleSort(arr):
    sort_list = [[]]
    n = len(arr)
    # optimize code, so if the array is already sorted, it doesn't need
    # to go through the entire process
    swapped = False
    print(arr)
    # Traverse through all array elements
    for i in range(n - 1):
        # range(n) also work but outer loop will
        # repeat one time more than needed.
        # Last i elements are already in place
        for j in range(0, n - i - 1):
            sort_list.append(arr)
            # traverse the array from 0 to n-i-1
            # Swap if the element found is greater
            # than the next element
            if arr[j] > arr[j + 1]:
                swapped = True
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

        if not swapped:
            # if we haven't needed to make a single swap, we
            # can just exit the main loop.
            return
    print("sorted arr", sort_list)
    
arr = [2,1,5,7,3]        
bubbleSort(arr)

The output I am getting is this:

[2, 1, 5, 7, 3]
sorted arr [[], [1, 2, 3, 5, 7], [1, 2, 3, 5, 7], [1,2, 3, 5, 7], [1, 2, 3, 5, 7],
[1, 2, 3, 5, 7], [1, 2, 3, 5, 7], [1, 2, 3, 5, 7], [1, 2, 3, 5, 7], [1, 2, 3, 5, 7],
[1, 2, 3, 5, 7]]

I have a feeling that I am doing something stupid but the logic seems so obvious that I cannot imagine why it doesn’t work.

Asked By: Bhola Saxena

||

Answers:

Does this work?

def bubbleSort(arr):
    sort_list = []
    n = len(arr)
    # optimize code, so if the array is already sorted, it doesn't need
    # to go through the entire process
    swapped = False
    print(arr)
    # Traverse through all array elements
    for i in range(n - 1):
        # range(n) also work but outer loop will
        # repeat one time more than needed.
        # Last i elements are already in place
        for j in range(0, n - i - 1):
            # traverse the array from 0 to n-i-1
            # Swap if the element found is greater
            # than the next element
            if arr[j] > arr[j + 1]:
                swapped = True
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
        sort_list.append(arr.copy())
        if not swapped:
            # if we haven't needed to make a single swap, we
            # can just exit the main loop.
            return
    print("sorted arr", sort_list)
    
arr = [7,5,3,2,1]        
bubbleSort(arr)

OUTPUT:

[[5, 3, 2, 1, 7], [3, 2, 1, 5, 7], [2, 1, 3, 5, 7], [1, 2, 3, 5, 7]]
Answered By: Salahuddin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.