Problem:


Bubble Sort

Write a program of the Bubble Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:

BubbleSort(A)
1 for i = 0 to A.length-1
2     for j = A.length-1 downto i+1
3         if A[j] N, the number of elements in the sequence.

In the second line, N elements of the sequence are given separated by spaces characters.

Output

The output consists of 2 lines. 

In the first line, please print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

In the second line, please print the number of swap operations.

Constraints

1 ≤ N ≤ 100

Sample Input 1

5
5 3 2 4 1

Sample Output 1

1 2 3 4 5
8

Sample Input 2

6
5 2 4 6 1 3

Sample Output 2

1 2 3 4 5 6
9



Sample input:
5
5 3 2 4 1


Sample output:
1 2 3 4 5
8

Submission status: Accepted

Solution code:

def print_result(arr, n):
    for i in range(n):
        if i > 0:
            print(' ', end='')
        print(arr[i], end='')
    print('\n', end='')


def bubble_sort(arr, n):
    flag = True
    i = 0
    sw_count = 0
    while flag:
        flag = False
        for j in range(n-1, i, -1):
            if arr[j] < arr[j-1]:
                arr[j], arr[j-1] = arr[j-1], arr[j]
                flag = True
                sw_count += 1
        i += 1
    return sw_count


n = eval(input())
arr = [eval(x) for x in input().split()]
sw = bubble_sort(arr, n)
print_result(arr, n)
print(sw)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(i) for i in input().split()]

flag = True

count = 0
while flag:
    flag = False
    for i in range(1, N):
        if A[i] < A[i - 1]:
            A[i], A[i - 1] = A[i - 1], A[i]
            flag = True
            count += 1

for i in range(N):
    print(A[i], end='')
    if i != N - 1:
        print(' ', end='')
print('')

print(count)

Submission status: Accepted

Solution code:
m=int(input())
n=list(map(int,input().split()))
cnt=0
flag=1
while flag:
  flag=0
  for j in range(m-1,0,-1):
    if n[j]<n[j-1]:
      n[j],n[j-1]=n[j-1],n[j]
      cnt+=1
      flag=1

print(' '.join(map(str, n)))
print(cnt)

Submission status: Accepted

Solution code:
# ALDS1_2_A - Bubble Sort
def main():
    N, *A = map(int, open(0).read().split())
    ans = 0
    for i in range(N):
        for j in range(N - 1, i, -1):
            if A[j] < A[j - 1]:
                A[j], A[j - 1] = A[j - 1], A[j]
                ans += 1
    print(*A)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
if __name__ == '__main__':
    N = int(input())
    A = list(map(int, input().split()))
    count=0
    flag = True
    while(flag):
        flag = False
        for i in range(N-1):
            if A[i] > A[i+1]:
                A[i], A[i+1] = A[i+1], A[i]
                count += 1
                flag = True
    print(*A)
    print(count)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))

flag = 1 #逆の隣接要素が存在する
cnt = 0
while flag :
	flag = 0
	for j in reversed(range(1,N)):
		if A[j]<A[j-1]:
			v = A[j]
			A[j] = A[j-1]
			A[j-1] = v
			flag = 1
			cnt += 1
print(" ".join(list(map(str,A))
))
print(cnt)

Submission status: Accepted

Solution code:
num = int(input())

lst = [int(x) for x in input().split()]

def show():
    for i in range(len(lst)):
        print(lst[i], end="")
        if i < len(lst)-1:
            print(" ", end="")
        else:
            print()

f = True
count = 0
while f:
    f = False
    for j in reversed(range(1,len(lst))):
        if lst[j] < lst[j-1]:
            tmp = lst[j]
            lst[j] = lst[j-1]
            lst[j-1] = tmp
            count += 1
            f = True
show()
print(count)

Submission status: Accepted

Solution code:
n = int(input())
li = list(map(int, input().split()))
flag = 0
for i in reversed(range(n)):
    for j in range(i):
        if li[j] > li[j+1]:
            li[j], li[j+1] = li[j+1], li[j]
            flag += 1

print(*li)
print(flag)

Submission status: Accepted

Solution code:
def test():

	n = int(input())
	A = list(map(int,input().split()))

	swap_count = 0
	for i in range(n):
		for j in range(n-1,i,-1):
			if A[j] < A[j-1]:
				swap_count += 1
				tmp = A[j]
				A[j] = A[j-1]
				A[j-1] = tmp

	for i in range(n-1):
		print(f"{A[i]} ",end = '')
	print(f"{A[n-1]}")
	print(swap_count)


if __name__ == "__main__":
	test()

Submission status: Accepted

Solution code:
#! /usr/bin/python
# -*- coding: utf-8 -*-

n=int(input()) # 数列の長さ
A=list(map(int, input().split())) # 空白を区切文字として配列に格納

tmp = 0
cnt = 0
flag = 1

while flag:
    flag = 0
    for i in range(1, n):
        j = n - i
        if A[j] < A[j-1]:
            tmp = A[j]
            A[j] = A[j-1]
            A[j-1] = tmp
            flag = 1
            cnt += 1
print(*A)
print(cnt)

Submission status: Accepted

Solution code:
n=int(input())
A=list(map(int,input().split()))
flag=1
count =0
while flag ==1:
    flag=0
    for j in range(n-1,0,-1):
        if A[j]<A[j-1]:
            A[j],A[j-1]= A[j-1],A[j]
            flag=1
            count+=1
print(" ".join(map(str,A)))
print(count)

Submission status: Accepted

Solution code:
N = int(input())
*A, = map(int, input().split())
flag = 1
i = 0
count = 0
while i < N-1:
    for j in range(N-1, i, -1):
        if A[j] < A[j-1]:
            tmp = A[j]
            A[j] = A[j-1]
            A[j-1] = tmp
            count += 1
    i += 1
        
print(*A)
print(count)

Submission status: Accepted

Solution code:
def bubbleSort(A, N):
    cnt = 0
    flag = 1
    while flag:
        flag = 0
        for j in range(N-1, 0, -1):
            if A[j] < A[j-1]:
                A[j], A[j-1] = A[j-1], A[j]
                flag = 1
                cnt += 1
    return A, cnt

N = int(input())
A = [int(_) for _ in input().split()]

A, cnt = bubbleSort(A, N)
print(" ".join([str(i) for i in A]))
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
A =[int(i) for i in input().split()]
count=0
for i in range(n):
	for j in range(n-1,i,-1):
		if A[j]<A[j-1]:
			A[j],A[j-1]=A[j-1],A[j]
			count+=1
print(' '.join(list(map(str,A))))
print(count)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
flag=True
count=0
while flag:
    flag=False
    for j in range(N-1, 0, -1):
        if A[j] < A[j-1]:
            tmp=A[j]
            A[j]=A[j-1]
            A[j-1]=tmp
            flag=True
            count=count+1

print(' '.join([str(a) for a in A]))
print("{}".format(count))

Submission status: Accepted

Solution code:

N = int(input())

A = list(map(int,input().split()))

num = 0

flag = True

while flag:

    flag = False

    for j in range(N-1):

        j = N-1-j

        if A[j] < A[j-1]:

            oaj = A[j]

            A[j] = A[j-1]
            A[j-1] = oaj

            flag = True

            num += 1

print (" ".join(map(str,A)))
print (num)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(x) for x in input().split()]

def BubbleSort(A):
    N = len(A)
    count = 0
    flag = 1
    i = 0
    while flag:
        flag = 0
        for j in reversed(range(i+1,N)):
            if A[j] < A[j-1]:
                A[j], A[j-1] = A[j-1], A[j]
                count += 1
                flag = 1
        i += 1
    for k in range(N-1):
        print(A[k], end=" ")
    print(A[N-1])
    print(count)

BubbleSort(A)

Submission status: Accepted

Solution code:
# バブルソート
def bubbleSort(list, n):
    cnt = 0  # 要素の交換回数
    for i in range(n-1):
        for j in reversed(range(i+1, n)):
            if list[j] < list[j-1]:
                list[j], list[j-1] = list[j-1], list[j]
                cnt += 1
    return cnt

N = int(input())
array = list(map(int, input().split()))
ans = bubbleSort(array, N)

print(array[0], end="")
for i in range(1, N):
    print(" %d" % array[i], end="")
print("\n%d" % ans)

Submission status: Accepted

Solution code:
r = int(input())
A = list(map(int, input().split()))

cnt = 0
for a in A:
    for i in range(r - 1, 0, -1):
        if A[i] < A[i-1]:
            A[i-1], A[i] = A[i], A[i-1]
            cnt+=1
print(" ".join(map(str, A)))
print(cnt)

Submission status: Accepted

Solution code:
#Bubble Sort

def printout(array, n):
    output = ""
    for i in range(n - 1):
        output += str(array[i]) + " "
    output += str(array[N - 1])
    print(output)


N = int(input())
array = [int(i) for i in input().split()]
count = 0;
for i in range(N):
    for j in reversed(range(i+1,N)):
        if (array[j-1] > array[j]):
            tmp = array[j]
            array[j] = array[j-1]
            array[j-1] = tmp
            count += 1
printout(array,N)
print(count)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
cnt=0
flag=1

for i in range(0,n-1):
    flag=0
    for j in reversed(range(i+1,n)):
        if a[j-1]>a[j]:
            ab=a[j-1]
            a[j-1]=a[j]
            a[j]=ab
            flag=1
            cnt+=1
def convert(list): 
    res=" ".join(map(str, list)) 
    return res   
print(convert(a))
print(cnt)

Submission status: Accepted

Solution code:
def getInput():
    n = int(input())
    a = [int(i) for i in input().split(" ")]
    return n, a

def swap(x, y):
    v = x
    x = y
    y = v
    return x, y

def bubbleSort(n, a):
    cnt = 0
    for j in range(n):
        init = True
        for i in range(n-1, -1, -1):
            if init:
                init = False
                continue
            if a[i] > a[i+1]:
                a[i], a[i+1] = swap(a[i], a[i+1])
                cnt += 1
    print(" ".join([str(i) for i in a]))
    print(cnt)
    return

n, a = getInput()
bubbleSort(n, a)

Submission status: Accepted

Solution code:
roop_num = int(input())
values = [int(value) for value in input().split()]

exchange_num = 0

while roop_num:
  for i in range(1,roop_num):
    if values[i - 1] > values[i]:
      values[i - 1], values[i] = values[i], values[i - 1]
      exchange_num += 1
  roop_num -= 1

ans = map(lambda value:str(value), values)

print(' '.join(ans).strip())
print(exchange_num)

Submission status: Accepted

Solution code:
def bubbleSort(A, N):
    count = 0
    for i in reversed(range(N)):
        for j in range(i):
            if A[j] > A[j+1]:
                # print(f"交換:{A[j]},{A[j+1]}")
                A[j], A[j+1] = A[j+1], A[j]
                count += 1
    output(A, count)

def output(A, N):
    for a in range(len(A)):
        if a == len(A)-1:
            print(A[a])
            print(N)
        else:
            print(A[a], end=" ")

def main():
    N = int(input())
    list = input().split(" ")
    list = [int(s) for s in list]
    
    bubbleSort(list, N)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    a = list(map(int, input().split(' ')))
    c = 0
    flag = 1
    while flag:
        flag = 0
        j = 0
        for i in range(n-1, j, -1):
            if a[i] < a[i-1]:
                a[i], a[i-1] = a[i-1], a[i]
                c += 1
                flag = 1
        j -= 1
    print(' '.join(map(str, a)))
    print(c)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
num_inputs = int(input())
array = input().split(' ')
flag = True
count = 0

while flag:
    flag = False
    for i in reversed(range(1, num_inputs)):
        if int(array[i]) < int(array[i - 1]):
            buf = array[i]
            array[i] = array[i - 1]
            array[i - 1] = buf
            count += 1
            flag = True

print(' '.join(array))
print(str(count))

Submission status: Accepted

Solution code:
def bubble_sort(A):
    flag = True
    swap = 0
    while flag:
        flag = False
        for j in range(len(A)-1,0,-1):
            if A[j] < A[j-1]:
                A[j],A[j-1] = A[j-1],A[j]
                swap += 1
                flag = True
    return swap
 
if __name__=='__main__':
   N=int(input()) 
   A=list(map(int,input().split()))
   swap = bubble_sort(A)
   print(*A)
   print(swap)

Submission status: Accepted

Solution code:
def bubblesort(array):
    flag = True
    res = 0
    while flag:
        flag = False
        for i in range(len(array)-1, 0, -1):
            if array[i] < array[i-1]:
                array[i], array[i-1] = array[i-1], array[i]
                res += 1
                flag = True
    return (array, res)
      
int(input())
arr, c = bubblesort([int(i) for i in input().split()])
print(*arr,sep=' ')
print(c)

Submission status: Accepted

Solution code:
from enum import Enum
import sys
import math
 
BIG_NUM = 2000000000
MOD = 1000000007
EPS = 0.000000001
 
 
N = int(input())
table = list(map(int,input().split()))
 
swap_count = 0
 
for i in range(0,len(table)-1): #最小値を持ってくる場所のループ
    for k in range(len(table)-1,i,-1):
        if table[k-1] > table[k]:
            table[k-1],table[k] = table[k],table[k-1]
            swap_count += 1
 
print(' '.join(map(str,table)))
print("%d"%(swap_count))

Submission status: Accepted

Solution code:
def bubblesort(a,n,c):
    c=0
    flag=1
    while flag:
        flag=0
        for j in range(n-1,0,-1):
            if a[j]<a[j-1]:
                m=a[j]
                a[j]=a[j-1]
                a[j-1]=m
                flag=1
                c+=1
    return a,c

n=int(input())
a=list(map(int,input().split()))
c=0
ans=bubblesort(a,n,c)
a=ans[0]
c=ans[1]
print(" ".join(map(str,a)))
print(c)

Submission status: Accepted

Solution code:
def bubbleSort(A,N):
    global cnt
    flag=1
    while flag:
        flag=0
        for j in range(N-1,0,-1):
            if A[j]<A[j-1]:
                A[j],A[j-1]=A[j-1],A[j]
                flag=1
                cnt+=1
N = int(input())
A = list(map(int,input().split()))
cnt = 0
bubbleSort(A,N)
print(*A)
print(cnt)

Submission status: Accepted

Solution code:
def bubblesort(array):
    flag = True
    res = 0
    while flag:
        flag = False
        for i in range(len(array)-1, 0, -1):
            if array[i] < array[i-1]:
                array[i], array[i-1] = array[i-1], array[i]
                res += 1
                flag = True
    return (array, res)
     
int(input())
arr, c = bubblesort([int(i) for i in input().split()])
print(*arr,sep=' ')
print(c)

Submission status: Accepted

Solution code:
n = int(input())
A = list(map(int,input().split(" ")))

def bubbleSort(n,A):
    c = 0
    flag = True
    while flag:
        flag = False
        for j in reversed(range(1,n)):
            if A[j] < A[j-1]:
                c+=1
                tmp = A[j]
                A[j] = A[j-1]
                A[j-1] = tmp
                flag = True
    return (A,c,)


R,C = bubbleSort(n,A)
print(" ".join(["{0["+ str(i) + "]}" for i in range(n)]).format(R))
print(C)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))

cnt = 0
flag = True
while flag:
  flag = False
  for i in reversed(range(1, N)):
    if A[i] < A[i-1]:
      A[i], A[i-1] = A[i-1], A[i]
      flag = True
      cnt += 1

print(" ".join(map(str, A)))
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
flag = 0
for i in range(n):
  for j in range(1,n):
    if a[j] < a[j-1]:
      a[j], a[j-1] = a[j-1], a[j]
      flag = flag + 1
for i in range(n):
    print(a[i], end="")
    if i == n-1:
        print("")
    else:
        print(" ", end="")
print(flag)

Submission status: Accepted

Solution code:
n = int(input())
nums = list(map(int, input().split()))

count = 0
for i in range(n):
    for j in range(n - 1, i, -1):
        if nums[j] < nums[j - 1]:
            nums[j - 1], nums[j] = nums[j], nums[j - 1]
            count += 1

print(' '.join(map(str, nums)))
print(count)

Submission status: Accepted

Solution code:
n = int(input())

A = [int(s) for s in input().split()]

cnt = 0
flag = True
while flag:
    flag = False
    for j in range(n-1, 0, -1):
        if A[j] < A[j-1]:
            A[j-1], A[j] = A[j], A[j-1]
            flag = True
            cnt += 1

print(*A)
print(cnt)

Submission status: Accepted

Solution code:
class inte:
	n = 0
	def __init__(self, n):
		self.n = n
	def chmax(self, n):
		self.n = n if self.n < n else self.n
	def chmin(self, n):
		self.n = n if self.n > n else self.n

N = int(input())
A = list(map(int, input().split()))

def sort(a):
	count = 0
	while True:
		for i in reversed(range(1, len(a))):
			if a[i] < a[i - 1]:
				a[i], a[i - 1] = a[i - 1], a[i]
				count += 1
				break
		else:
			return count

count = sort(A)
print(*A)
print(count)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
count = 0

flag = 1
while flag:
    flag = 0
    for j in range(1, n):
        num = a[j]
        if a[j] < a[j-1]:
            a[j] = a[j-1]
            a[j-1] = num
            count += 1
            flag = 1

print(*a, sep=' ')
print(count)

Submission status: Accepted

Solution code:

def BubleSort(N, data):
    flag = 1
    cnt = 0
    while flag:
        flag = 0
        for i in range(N-1, 0, -1):
            if data[i] < data[i-1]:
                data[i], data[i-1] = data[i-1], data[i]
                flag = 1
                cnt = cnt + 1
    return data, cnt

N = int(input())
data = [ int(i) for i in input().split()]

new_data, cnt = BubleSort(N, data)

for n in range(N):
    if n:
        print(" ", end="")
    print(data[n], end="")
print()
print(cnt)

Submission status: Accepted

Solution code:
count = int(input())
numbers = input().split(" ")
for i in range(len(numbers)):
    numbers[i] = int(numbers[i])


if __name__ == "__main__":
    swap_count = 0

    flag = True
    while flag:
        flag = False
        for j in range(count-1, 0, -1):
            if numbers[j] < numbers[j-1]:
                numbers[j], numbers[j-1] = numbers[j-1], numbers[j]
                swap_count += 1
                flag = True

    print(*numbers)
    print(swap_count)

Submission status: Accepted

Solution code:
n = int(input())
bubble=list(map(int,input().split()))
count = 0
for i in  range(len(bubble)):
    for a in range(len(bubble)-1):
        if (bubble[a] > bubble[a+1]):
            bubble[a], bubble[a+1] = bubble[a+1], bubble[a]
            count = count+1
print(*bubble)
print(count)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))

def bubble_sort(a, n):
    counter = 0
    for i in range(n-1, 0, -1):
        for j in range(i):
            if a[j] > a[j+1]:
                a[j], a[j+1] = a[j+1], a[j]
                counter += 1

    return a, counter

a, counter = bubble_sort(a, n)
print(" ".join(map(str, a)))
print(counter)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int, input().split()))
cnt=0
flg=1
while flg:
  flg=0
  for i in range(1,N)[::-1]:
    if A[i] < A[i-1]:
      _=A[i]
      A[i]=A[i-1]
      A[i-1]=_
      flg=1
      cnt+=1
print(*A)
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
*A, = map(int, input().split())
 
ans = 0
for i in range(n):
    for j in range(n-1):
        if A[j+1] < A[j]:
            A[j], A[j+1] = A[j+1], A[j]
            ans += 1
print(*A)
print(ans)

Submission status: Accepted

Solution code:
def bubble_sort(A):
    num = 0
    for i in range(len(A)):
        for j in range(len(A)-1, i, -1):
            if A[j] < A[j-1]:
                tmp = A[j]
                A[j] = A[j-1]
                A[j-1] = tmp
                num += 1
                
    print(' '.join(list(map(str, A))))
    print(num)

n = input()
A = list(map(int, input().split()))
bubble_sort(A)

Submission status: Accepted

Solution code:
def bubbleSort(A, N):
    count = 0
    flag = 1
    while flag:
        flag = 0
        j = N-1
        while j != 0:
            if A[j] < A[j-1]:
                out = A[j-1]
                A[j-1] = A[j]
                A[j] = out
                flag = 1
                count += 1
            j -= 1
    print(' '.join(map(str, A)))
    print(str(count))
            
if __name__ == '__main__':
    N = int(input()) #1行目のNを取得する
    M = list(map(int,input().split()))
    bubbleSort(M, N)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
flag = True
cnt = 0
while flag:
    flag = False
    for j in range(n - 1, 0, -1):
        if a[j] < a[j-1]:
            a[j-1], a[j] = a[j], a[j-1]
            cnt += 1
            flag = True
print(' '.join(list(map(str, a))))
print(cnt)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))

def bubbleSort(A, N):
    counter = 0
    flag = 1
    i = 0
    while flag:
        flag = 0
        for j in range(N-1, i, -1):
            if A[j] < A[j-1]:
                temp = A[j-1]
                A[j-1] = A[j]
                A[j] = temp
                counter += 1
                flag = 1
        i +=1
    return A,counter
    
A, counter = bubbleSort(A, N)

print(' '.join(repr(e) for e in A))
print(counter)

Submission status: Accepted

Solution code:
# coding=utf-8

###
### for atcorder program
###

import sys
import math

# math class
class mymath:
    ### pi
    pi = 3.14159265358979323846264338

    ### Prime Number
    def pnum_eratosthenes(self, n):
        ptable = [0 for i in range(n+1)]
        plist = []

        for i in range(2, n+1):
            if ptable[i]==0:
                plist.append(i)
                for j in range(i+i, n+1, i):
                    ptable[j] = 1
        return plist

    ### GCD
    def gcd(self, a, b):
        if b == 0:
            return a
        return self.gcd(b, a%b)

    ### LCM
    def lcm(self, a, b):
        return (a*b)//self.gcd(a,b)

    ### Mat Multiplication
    def mul(self, A, B):
        ans = []
        for a in A:
            c = 0
            for j, row in enumerate(a):
                c += row*B[j]
            ans.append(c)
        return ans

mymath = mymath()

### output class
class output:
    ### list
    def list(self, l):
        l = list(l)
        #print(" ", end="")
        for i, num in enumerate(l):
            print(num, end="")
            if i != len(l)-1:
                print(" ", end="")
        print()

output = output()

### input sample
#i = input()
#N = int(input())
#A, B, C = [x for x in input().split()]
#N, K = [int(x) for x in input().split()]
#inlist = [int(w) for w in input().split()]

#R = float(input())
#A.append(list(map(int,input().split())))

#for line in sys.stdin.readlines():
#    x, y = [int(temp) for temp in line.split()]

#abc list
#abc = [chr(ord('a') + i) for i in range(26)]

### output sample
#print("{0} {1} {2:.5f}".format(A//B, A%B, A/B))
#print("{0:.6f} {1:.6f}".format(R*R*math.pi,R*2*math.pi))
#print(" {}".format(i), end="")

# リスト内包表記 ifあり
# [x-k if x != 0 else x for x in C]

# ソート
# N = N.sort()

# 10000個の素数リスト
# P = mymath.pnum_eratosthenes(105000)

def get_input():
    N = []
    while True:
        try:
            N.append(input())
            #N.append(int(input()))
            #N.append(float(input()))
        except EOFError:
            break
    return N

def is_integer(n):
    try:
        float(n)
    except ValueError:
        return False
    else:
        return float(n).is_integer()

def dist(A, B):
    d = 0
    for i in range(len(A)):
        d += (A[i]-B[i])**2            
    d = d**(1/2)
    return d


N = int(input())
A = [int(x) for x in input().split()]

#print(list(range(N-1, 0, -1)))

count = 0
for i in range(N-1):
    for j in range(N-1, i, -1):
        if A[j] < A[j-1]:
            A[j], A[j-1] = A[j-1], A[j]
            count += 1

for i, n in enumerate(A):
    print(n, end='')
    if i != N-1:
        print(' ', end='')
print()

print(count)

Submission status: Accepted

Solution code:
def bubblesort(A, n):
    flag = 1
    count = 0
    while flag:
        flag = 0
        for i in range(1,n):
            if A[n-i] < A[n-i-1]:
                A[n-i], A[n-i-1] = A[n-i-1], A[n-i]
                count = count + 1
                flag = 1
        
    A_str = [str(a) for a in A]
    A_str = " ".join(A_str)
    print(A_str)
    print(count)

n = int(input())
A = list(map(int, input().split()))
bubblesort(A, n)

Submission status: Accepted

Solution code:
def bubble_sort(elems: list) -> list:
    swap_num = 0
    for i in range(0, len(elems)):
        for j in range(len(elems) - 1, i, -1):
            if elems[j] < elems[j - 1]:
                elems[j], elems[j - 1] = elems[j - 1], elems[j]
                swap_num += 1
    return [elems, swap_num]


if __name__ == "__main__":
    elem_num = int(input())
    elems = list(map(lambda x: int(x), input().split()))
    elems, swap_num = bubble_sort(elems)
    print(" ".join([str(elem) for elem in elems]))
    print(f"{swap_num}")

Submission status: Accepted

Solution code:
def show(A):
    L = list(map(str, A))
    print(" ".join(L))

N = int(input())
A = list(map(int, input().split()))
flag = True
cnt = 0

while flag:
    flag = False
    for j in range(N-1, 0, -1):
        if A[j] < A[j-1]:
            A[j], A[j-1] = A[j-1], A[j]
            flag = True
            cnt += 1

show(A)
print(cnt)

Submission status: Accepted

Solution code:
def bubble_sort(A):
    flag = True
    swap = 0
    while flag:
        flag = False
        for j in range(len(A)-1,0,-1):
            if A[j] < A[j-1]:
                A[j],A[j-1] = A[j-1],A[j]
                swap += 1
                flag = True
    return swap
  
if __name__=='__main__':
   N=int(input()) 
   A=list(map(int,input().split()))
   swap = bubble_sort(A)
   print(*A)
   print(swap)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    array = [int(i) for i in input().split(' ')]

    count = 0
    for i in range(n):
        for j in range(n-1, i, -1):
            if array[j] < array[j-1]:
                count += 1
                array[j], array[j-1] = array[j-1], array[j]
    print(' '.join(map(str, array)))
    print(count)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# 冒泡排序
def bubble_sort(arr):
    no_swap = True
    swap_cnt = 0
    for i in range(len(arr), 0, -1):
        if not no_swap:
            break
        for j in range(0, i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swap_cnt += 1
            no_swap = True
    return swap_cnt


if __name__ == '__main__':
    N = int(input())
    arr = list(map(int, input().split()))
    cnt = bubble_sort(arr)
    print(' '.join(map(str, arr)))
    print(cnt)

Submission status: Accepted

Solution code:
from sys import stdin
N = int(stdin.readline().rstrip())
nums = [int(_) for _ in stdin.readline().rstrip().split()]

def bubble_sort(a, n):
    count = 0
    flag = 1
    while flag:
        flag = 0
        for i in range(N-1, 0, -1):
            if a[i] < a[i-1]:
                a[i], a[i-1] = a[i-1], a[i]
                flag = 1
                count += 1
    return a, count

ret, count = bubble_sort(nums, N)
print(*ret)
print(count)

Submission status: Accepted

Solution code:

if __name__ == '__main__':
    n = int(raw_input())
    A = map(int, raw_input().split())
    cnt = 0
    for i in range(0, n):
        for j in range(n - 1, i, -1):
            if A[j - 1] > A[j]:
                A[j - 1], A[j] = A[j], A[j - 1]
                cnt += 1
    for x in A:
        print x,
    print
    print cnt

Submission status: Accepted

Solution code:
N = int(input())

A = []

nums = input().split()

for i in range(N):
    A.append(int(nums[i]))

    

flag = 1
a = 0
cnt = 0

while flag:
    flag = 0
    for i in reversed(range(a+1, N)):
        if A[i] < A[i-1]:
            A[i], A[i-1] = A[i-1], A[i]
            cnt += 1
            flag = 1
    a += 1

l = [str(i) for i in A]
print(" ".join(l))
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
array = list(map(int, input().split()))

flag = 1
count = 0
while flag:
    flag = 0
    for i in range(1, n)[::-1]:
        if array[i] < array[i-1]:
            array[i], array[i-1] = array[i-1], array[i]
            flag = 1
            count += 1
print(' '.join(list(map(str, array))))
print(count)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))

c=0
for i in range(len(A)):
    for j in range(1,len(A)):
        if A[j] < A[j-1]:
            temp=A[j-1]
            A[j-1]=A[j]
            A[j]=temp
            c+=1
print(*A)
print(c)

Submission status: Accepted

Solution code:
def p(a):
    for i in a[:-1]:
        print(i,end=' ')
    print(a[-1])


def bubble_sort(a):
    cnt = 0
    for i in range(len(a)-1):
        for j in range(i+1,len(a))[::-1]:
            if a[j-1]>a[j]:
                cnt+=1
                tmp = a[j]
                a[j] = a[j-1]
                a[j-1] = tmp
    p(a)
    print(cnt)


n = int(input())
l = list(map(int,input().split()))
bubble_sort(l)

Submission status: Accepted

Solution code:
def hyoji(l):
    for i in range(len(l)):
        if i != len(l) - 1:
            print(l[i], end = ' ')
        else:
            print(l[i])

n = int(input())
A = list(map(int, input().split()))

c = 0
for j in range(len(A)):
    for k in range(len(A) - 1, j, -1):
        if A[k] < A[k - 1]:
            A[k], A[k - 1] = A[k-1], A[k]
            c += 1
hyoji(A)
print(c)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
cnt=0
for i in range(n):
    judge=False
    for j in range(i+1,n)[::-1]:
        if a[j-1]>a[j]:
            a[j-1],a[j]=a[j],a[j-1]
            judge=True
            cnt+=1

print(*a)
print(cnt)

Submission status: Accepted

Solution code:
def print_format(N,input_list, count):
    for i in range(N):
        if i != N-1:
            print(input_list[i],end=" ")
        else :
            print(input_list[i])
    print(count)
def bubble_sort(N,input_list):
    count = 0
    flag = True
    while flag:
        flag = False
        for j in range(1,N)[::-1]:
            if input_list[j] < input_list[j-1]:
                input_list[j],input_list[j-1] = input_list[j-1],input_list[j]
                count += 1
                flag = True
    return input_list, count

def main():
    N = int(input())
    input_list = [int(i) for i in input().split()]
    input_list,count = bubble_sort(N,input_list)
    print_format(N,input_list,count)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
As = list(map(int, input().split()))

cnt = 0
flg = True
while flg:
    flg = False
    for i in range(N-1,0,-1):
        if As[i-1] > As[i]:
            tmp = As[i]
            As[i] = As[i-1]
            As[i-1] = tmp        
            flg = True
            cnt += 1
print(" ".join([str(a) for a in As]))
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))

f = True
ans = 0

while f:
    f = False
    for i in range(1, len(a)):
        if a[i] < a[i - 1]:
            ans += 1
            a[i], a[i - 1] = a[i - 1], a[i]
            f = True

print(*a)
print(ans)

Submission status: Accepted

Solution code:
length = int(input())
List = list(map(int,input().split()))

count = 0
state = 1

while state:
    state = 0
    for i in range(length-1):
        if List[i] > List[i+1]:
            stuck = List[i]
            List[i] = List[i+1]
            List[i+1] = stuck
            state = 1
            count += 1

for i in range(length):
    if i == length - 1:
        print(List[length-1])
    else: print(List[i],end=' ')
print(count)