Loop through an array; compare every two elements next to each other; swap position if previous one is larger than subsequent one.
JavaScript Implement
Basic version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** * Bubble Sort * @param {Number[]} array - The original array which is not ordered * @returns {Number[]} */ functionbubbleSort(array) { for (let i = 0; i < array.length - 1; i++) { for (let j = 0; j < array.length - 1 - i; j++) { if (array[j] > array[j + 1]) { const temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } return array; }
Improvement version 1
To swap two elements in an array, we can also use array destructing in ES6, referring this article.
1 2 3 4 5 6 7 8 9 10
functionbubbleSort(array) { for (let i = 0; i < array.length - 1; i++) { for (let j = 0; j < array.length - 1 - i; j++) { if (array[j] > array[j + 1]) { [array[j], array[j + 1]] = [array[j + 1], array[j]]; } } } return array; }
There are other methods to swap two array elements in JavaScript, referring this article.
Improvement version 2
A concept to grasp before make another improvement – Pure Function. Two points to note on Pure Function.
Given the same input, always returns the same output
Produces no side effects
Here we can tell the above implement satisfies first point but not second point. It mutates (which is considered as a side effect) the state of the parameter passed to the function. Let’s check.
The above two improvements are more from cosmetic point of view. Another improvement I found online is to introduce a flag to check if any swap happens in the inner loop. If no swap, meaning the array is sorted, we can change flag value and break the outer loop.
Note this sorting logic also works on character array, then how to annotate both types in TypeScript? TypeScript has a concept of generics which quoted below:
In TypeScript, generics are used when we want to describe a correspondence between two values. We do this by declaring a type parameter in the function signature. Tweaking the above a bit,
Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted. Best Case Time Complexity: O(n). Best case occurs when array is already sorted. Auxiliary Space: O(1) Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted. Sorting In Place: Yes Stable: Yes
The meaning of stable is if there are element with same value, their sequence in the result and in the parameter is unchanged thus stable.
Use case
Suitable for sort an array which is almost sorted. Not very practical in real-life business transactions.