You are viewing a single comment's thread. Return to all comments →
function bubbleSort(array: number[]): void { let endPosition: number = array.length - 1; let numberOfSwaps: number = 0; let swapPosition: number; while (endPosition > 0) { swapPosition = 0; for (let i = 0; i < array.length - 1; i++) { if (array[i] > array[i + 1]) { [array[i], array[i + 1]] = [array[i + 1], array[i]]; swapPosition = i; numberOfSwaps++; } } endPosition = swapPosition; } console.log(`Array is sorted in ${numberOfSwaps} swaps.`); console.log(`First Element: ${array[0]}`); console.log(`Last Element: ${array[array.length - 1]}`); } function main() { const n: number = parseInt(readLine().trim(), 10); const a: number[] = readLine().replace(/\s+$/g, '').split(' ').map(aTemp => parseInt(aTemp, 10)); bubbleSort(a); }
Seems like cookies are disabled on this browser, please enable them to open this website
Day 20: Sorting
You are viewing a single comment's thread. Return to all comments →
JavaScript