Skip to content

Instantly share code, notes, and snippets.

@yamadayuki
Created December 8, 2016 18:55
Show Gist options
  • Save yamadayuki/b13f43bad4de5e01e9e7bf6b7ff6c2de to your computer and use it in GitHub Desktop.
Save yamadayuki/b13f43bad4de5e01e9e7bf6b7ff6c2de to your computer and use it in GitHub Desktop.
Bubble Sort
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_2_A
// Test Case
// Input
// 6
// 5 2 4 6 1 3
// Output
// 1 2 3 4 5 6
// 9
var input = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n');
var n = +input.shift();
var nums = input.shift().split(' ').map(Number);
var swapTimes = 0;
function bubbleSort(numbers) {
for (var i = 0; i < numbers.length; i++) {
for (var j = numbers.length; j > i; j--) {
if (numbers[j] < numbers[j - 1]) {
var tmp = numbers[j];
numbers[j] = numbers[j - 1];
numbers[j - 1] = tmp;
swapTimes++;
}
}
}
console.log(numbers.join(' '));
console.log(swapTimes);
}
bubbleSort(nums);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment