Implementation
Let’s code bubble sort. It’s one of the simplest sorting algorithms to implement.
Basic Implementation
function 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 elements
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
# Swap elements
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
function bubbleSort(arr: number[]): number[] {
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 elements
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
Try It Yourself
🟨 JavaScript Bubble Sort Implementation
📟 Console Output
Run code to see output...
Code Explanation
-
Outer loop (
i): Runs n-1 times- After each iteration, one more element is in place
-
Inner loop (
j): Compares adjacent elements- Goes from 0 to n-i-1 (shrinks each pass)
-
Comparison:
arr[j] > arr[j + 1]- Checks if elements are out of order
-
Swap: Exchanges elements if needed
- Uses destructuring for clean swap
Edge Cases
Handle these scenarios:
- Empty array: Returns empty array (loops don’t run)
- Single element: Already sorted, returns as-is
- Already sorted: Still runs all passes (inefficient)
- All same values: No swaps needed, but still runs
Optimized Version
We can optimize by stopping early if no swaps occur:
🟨 JavaScript Optimized Bubble Sort
📟 Console Output
Run code to see output...
What’s Next?
Now that you can implement it, let’s analyze its performance and complexity.
Progress 57%
Page 4 of 7
← Previous
→ Next