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] < A[j-1]
4 swap A[j] and A[j-1]

Note that, indices for array elements are based on 0-origin.

Your program should also print the number of swap operations defined in line 4 of the pseudocode.

Input

The first line of the input includes an integer 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

Solution in JAVA (judge verdict: Accepted)

import java.util.Scanner;

/**
 * ZAKIREN第5章
 *
 * @author K.Yamauchi
 *
 */
public class Main {

	/**
	 *
	 * @param args
	 */
	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in); // 入力
		int n = Integer.parseInt(scan.nextLine()); // 要素数

		// ソート対象配列の読み込み
		String[] targetArrayStr = scan.nextLine().split(" ");
		int[] targetArray = new int[targetArrayStr.length];
		for (int i = 0; i < targetArrayStr.length; i++) {
			targetArray[i] = Integer.parseInt(targetArrayStr[i]);
		}

		// 読み込み終了
		scan.close();

		// ソート
		int exchangingCount = bubbleSort(n, targetArray);

		// 結果出力
		for (int i = 0; i < targetArray.length; i++) {
			if (i < targetArray.length - 1) {
				System.out.print(targetArray[i] + " ");
			} else {
				System.out.println(targetArray[i]);
			}
		}
		System.out.println(exchangingCount);;

	}

	/**
	 * 指定された整数配列をバブルソートする。
	 *
	 * @param n 配列の要素数
	 * @param targetArray バブルソートしたい整数配列
	 */
	private static int bubbleSort(int n, int[] targetArray) {
		boolean isNotSorted = true; // ソート未完了フラグ
		int exchangingCount = 0; // 入れ替え回数

		// ソートが完了するまで
		while (isNotSorted) {
			isNotSorted = false;

			// 天秤を右端から移動していく
			for (int i = n - 1; i > 0; i--) {
				// 自分より小さい値が左側に居たら
				if (targetArray[i] < targetArray[i - 1]) {
					// 2つの要素を入れ替える
					exchangeArrayValue(targetArray, i, i - 1);
					isNotSorted = true;
					exchangingCount++;
				}
			}
		}

		return exchangingCount;
	}

	/**
	 * 配列内の2つの要素を入れ替える。
	 *
	 * @param array 入れ替えたい要素を含む配列
	 * @param a 入れ替えたい要素のindex
	 * @param b 入れ替えたい要素のindex
	 */
	private static void exchangeArrayValue(int[] array, int a, int b) {
		int temp = array[a];
		array[a] = array[b];
		array[b] = temp;
	}

}