0% found this document useful (0 votes)
4 views2 pages

Ss 2

Bubble sort is a simple sorting algorithm that compares and swaps adjacent values, making it primarily useful for educational purposes due to its inefficiency. Its best-case time complexity is O(N) while the worst-case is O(N^2). The provided implementation includes an optimization to reduce unnecessary comparisons by adjusting the inner loop's range.

Uploaded by

sivangsantonino
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Ss 2

Bubble sort is a simple sorting algorithm that compares and swaps adjacent values, making it primarily useful for educational purposes due to its inefficiency. Its best-case time complexity is O(N) while the worst-case is O(N^2). The provided implementation includes an optimization to reduce unnecessary comparisons by adjusting the inner loop's range.

Uploaded by

sivangsantonino
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Bubble Sort

Best: O(N), Worst: O(N^2)

The bubble sort is a good starting point since it is one of the simplest sorting algorithms. It's
mostly just good for teaching purposes though since it is one of the slowest sorting
algorithms.

In short, the bubble sort algorithm compares every two adjacent values and swaps them if
the first one is bigger than the second one. This reflects its name since the values tend to
move up into the correct order, like bubbles rising to the surface.

function bubbleSort(arr, compare = defaultCompare) {


const { length } = arr;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - 1 - i; j++) { // refer to note below
if (compare(arr[j], arr[j + 1]) === Compare.BIGGER_THAN) {
swap(arr, j, j + 1);
}
}
}
return arr;
}

Note that the solution I provided is a slightly improved version of the usual bubble sort
algorithm since we are subtracting the number of passes from the inner loop to avoid
unnecessary comparisons. To get a better understanding of what's actually happening, here is
a diagram with an example:

You might also like