MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / bubbleSort

Function bubbleSort

Sorts/BubbleSort.js:19–41  ·  view source on GitHub ↗
(items)

Source from the content-addressed store, hash-verified

17 * Using 2 for loops.
18 */
19export function bubbleSort(items) {
20 const length = items.length
21 let noSwaps
22
23 for (let i = length; i > 0; i--) {
24 // flag for optimization
25 noSwaps = true
26 // Number of passes
27 for (let j = 0; j < i - 1; j++) {
28 // Compare the adjacent positions
29 if (items[j] > items[j + 1]) {
30 // Swap the numbers
31 ;[items[j], items[j + 1]] = [items[j + 1], items[j]]
32 noSwaps = false
33 }
34 }
35 if (noSwaps) {
36 break
37 }
38 }
39
40 return items
41}
42
43/**
44 * Using a while loop and a for loop.

Callers 1

BubbleSort.test.jsFile · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected