Search code examples
pythonalgorithmsortingbubble-sort

can this sorting algorithm be considered as a variation of bubble sort?


can this approach be considered a variation of bubble sort? if not then what are the key differences and what is the efficiency comparison between this approach and bubble sort?

def bubble_sort(arr):

    for i in range(len(arr)):
        for j in range(len(arr)-i):
            if arr[i] > arr[j+i]:
                arr[i], arr[j+i] = arr[j+i], arr[i]
    return arr


if __name__ == '__main__':
    arr = [21,4,1,3,9,20,25,6,21,14]
    print(bubble_sort(arr))

output: [1, 3, 4, 6, 9, 14, 20, 21, 21, 25]


Solution

  • Your code has implemented the algorithm selection sort rather than bubble sort. Though they are somewhat similar: they are both based on element swapping.

    For selection sort, the algorithm's key though is to find the minimal or maximum element and swap at last:

    The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.

    And your code can be improved to avoid unnecessary swaping:

    import random
    
    def my_sort(arr):
    
        for i in range(len(arr)):
            min_idx = i
            for j in range(len(arr)-i):
                if arr[min_idx] > arr[j+i]:
                    min_idx = j + i
            arr[i],arr[min_idx] = arr[min_idx], arr[i]
        return arr
    
    
    if __name__ == '__main__':
        for i in range(360):
            i = i + 1
            r = random.choices(range(i * 10), k=i)   # Get list of numbers
            r1 = r.copy()
            assert my_sort(r) == sorted(r1)