• + 0 comments
    def bubble(array):
        total_swaps = 0
        for i in range(len(array)):
            # track swaps in single array traversal
            number_of_swaps = 0
            for j in range(len(array) - 1):
                # swap adjacent elements if they're in the wrong order
                if array[j] > array[j + 1]:
                    temp = array[j]
                    array[j] = array[j + 1]
                    array[j + 1] = temp
                    number_of_swaps += 1
            # if no swaps, array is sorted
            if number_of_swaps == 0:
                break
            total_swaps += number_of_swaps
        return total_swaps, array[0], array[-1]
                    
    
    
    if __name__ == '__main__':
        n = int(input().strip())
    
        a = list(map(int, input().rstrip().split()))
    
        swaps, first, last = bubble(a)
        print(f'Array is sorted in {swaps} swaps.')
        print(f'First Element: {first}')
        print(f'Last Element: {last}')