Skip to content

Instantly share code, notes, and snippets.

@yamadayuki
Created December 8, 2016 19:04
Show Gist options
  • Save yamadayuki/03c2258105934f8f7016e3743563c161 to your computer and use it in GitHub Desktop.
Save yamadayuki/03c2258105934f8f7016e3743563c161 to your computer and use it in GitHub Desktop.
Selection Sort
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_2_B
// Test Case
// Input
// 6
// 5 2 4 6 1 3
// Output
// 1 2 3 4 5 6
// 3
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 selectionSort(numbers) {
for (var i = 0; i < numbers.length; i++) {
var minIndex = i;
for (var j = i; j < numbers.length; j++) {
if (numbers[j] < numbers[minIndex]) minIndex = j;
}
if (minIndex !== i) {
var tmp = numbers[i];
numbers[i] = numbers[minIndex];
numbers[minIndex] = tmp;
swapTimes++;
}
}
console.log(numbers.join(' '));
console.log(swapTimes);
}
selectionSort(nums);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment