Skip to content

Instantly share code, notes, and snippets.

@rakibulalam
Created May 21, 2020 21:44
Show Gist options
  • Save rakibulalam/cae58b5f3796a4cabdb2e63b00400974 to your computer and use it in GitHub Desktop.
Save rakibulalam/cae58b5f3796a4cabdb2e63b00400974 to your computer and use it in GitHub Desktop.
Sorting: Bubble Sort Hacker Rank
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', function () {
inputString = inputString.replace(/\s*$/, '')
.split('\n')
.map(str => str.replace(/\s*$/, ''));
main();
});
function readLine() {
return inputString[currentLine++];
}
// Complete the countSwaps function below.
function countSwaps(a) {
const n = a.length;
let numberOfSwap = 0;
for (let i = 0; i < n - 1; i++) {
let isSwaped = false;
for (let j = 0; j < n - i - 1; j++) {
if (a[j] > a[j + 1]) {
if (a[j] > a[j + 1]) {
[a[j], a[j + 1], isSwaped] = [a[j + 1], a[j], true];
numberOfSwap++;
}
}
}
if (isSwaped === false) {
break;
}
}
console.log(`Array is sorted in ${numberOfSwap} swaps.`)
console.log(`First Element: ${a[0]}`)
console.log(`Last Element: ${a[n - 1]}`)
}
function main() {
const n = parseInt(readLine(), 10);
const a = readLine().split(' ').map(aTemp => parseInt(aTemp, 10));
countSwaps(a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment