The task is to implement a bubble sort which sorts an integer array in ascending order, modifying it in place.
The boilerplate code:
function bubbleSort(arr) {
// your code here
}
The BubbleSort is a sorting algorithm that sorts an array by comparing adjacent elements in an array, and swaps them if they are in the wrong order.
The outer loop ensures we go through the loop multiple times
for(let i = 0; i < arr.length - 1; i++) {
}
The inner loop compares adjacent elements
for(let j = 0; j < arr.length-1; j++) {
}
If the current element is larger than the next element, we swap them using a temporary variable
if (arr[j] > arr[j + 1]) {
const temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
After every inner loop, one large element towards the end. The sorting is completed when the array loops one time less than the length of the array.
The final code:
function bubbleSort(arr) {
// your code here
for(let i = 0; i < arr.length - 1; i++) {
for(let j = 0; j < arr.length - 1; j++) {
if(arr[j] > arr[j + 1]) {
const temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp
}
}
}
}
That's all folks!
Top comments (0)