Sort by

recency

|

621 Discussions

|

  • + 0 comments

    Python 3 code if name == 'main': n = int(input().strip())

    a = list(map(int, input().rstrip().split()))
    
    swapy = 0
    for i in range(n):
        for j in range(n-1):
            wartosc = int()
            if (a[j] > a[j + 1]):
                wartosc = a[j]
                a[j] = a[j + 1]
                a[j + 1] = wartosc
                swapy += 1
    
    print("Array is sorted in "+str(swapy)+ " swaps.")
    print("First Element: " +str(a[0]))
    print("Last Element: " + str(a[-1]))
    
  • + 0 comments

    Python Code:

    if __name__ == '__main__':
        n = int(input().strip())
    
        a = list(map(int, input().rstrip().split()))
        
        swap = 0
        for i in range(n):
            for j in range(i, n):
                if a[i]>a[j]:
                    a[i], a[j] = a[j], a[i]
                    swap+=1
                    
        print(f"Array is sorted in {swap} swaps.")
        print(f"First Element: {a[0]}")
        print(f"Last Element: {a[-1]}")
    
  • + 0 comments

    **Python code: **

    if __name__ == '__main__':
        n = int(input().strip())
    
        a = list(map(int, input().rstrip().split()))
        
        swapy = 0
        for i in range(n):
            for j in range(n-1):
                wartosc = int()
                if (a[j] > a[j + 1]):
                    wartosc = a[j]
                    a[j] = a[j + 1]
                    a[j + 1] = wartosc
                    swapy += 1
                    
        print("Array is sorted in "+str(swapy)+ " swaps.")
        print("First Element: " +str(a[0]))
        print("Last Element: " + str(a[-1]))
    
  • + 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}')
    
  • + 0 comments

    for i in range(n): for j in range(i+1): if a[i] < a[j]: a[i], a[j] = a[j], a[i] temp += 1 print(f"Array is sorted in {temp} swaps.") print(f"First Element: {a[0]}") print(f"Last Element: {a[-1]}")