Bubble Sort
Implement a function that sorts an array using the bubble sort algorithm.
Advanced
Instructions
Bubble Sort is a sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
Implement a function bubbleSort
that takes an array of integers as input and returns the sorted array using the Bubble Sort algorithm.
The function should have the following signature:
const bubbleSort = (myArray) => {...}
The function should return an array of integers in non-decreasing order.
For example, bubbleSort([9,4,2,1,5])
should return [1,2,4,5,9]
.
Tip
The Bubble Sort algorithm works as follows:
- Start with the first element in the array.
- Compare it with the next element.
- If the first element is greater than the next element, swap them.
- Move to the next element and repeat steps 2 and 3.
- Continue this process until no swaps are needed.
PS: The checks doesn't check if you sorted the array correctly using bubble sort, just if the array is sorted. Make you best.
See Solution
Solution
const bubbleSort = (arr) => {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
for (let j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
Algorithm Detailed Explanation
- The outer loop runs from 0 to n-1, where n is the number of elements in the array.
- The inner loop runs from 0 to n-i-1, where i is the current iteration of the outer loop.
- In each iteration of the inner loop, we compare adjacent elements and swap them if they are in the wrong order.
- After each iteration of the outer loop, the largest element in the unsorted part of the array bubbles up to its correct position.
- The algorithm repeats this process until no swaps are needed, indicating that the array is sorted.
Complexity Analysis
- Time complexity: O(n^2) in the worst case, where n is the number of elements in the array.
- Space complexity: O(1) as the algorithm sorts the array in place without using any extra space.