Bubble sort is the simplest sort to picture: walk along the array comparing neighbours, and swap any pair that's in the wrong order. After one pass the largest value has "bubbled" all the way to the end. Repeat until a pass makes no swaps.
nums[0] and nums[1]; if the left one is bigger, swap them. Move one step right and repeat to the end.Each step compares one pair of neighbours. Watch the sorted part grow from the right.
function bubbleSort(nums) { const n = nums.length; for (let pass = 0; pass < n - 1; pass++) { let swapped = false; for (let j = 0; j < n - 1 - pass; j++) { // the last pass values are already in place if (nums[j] > nums[j + 1]) { [nums[j], nums[j + 1]] = [nums[j + 1], nums[j]]; // swap the out-of-order neighbours swapped = true; } } if (!swapped) break; // a pass with no swaps: sorted } return nums;}In the worst case (a reversed array) every pass swaps every pair: about n²/2 comparisons and swaps, O(n²). On an already sorted array the first pass makes no swaps and the loop stops: O(n). It only ever swaps neighbours in place, so the extra space is O(1).
Almost never in real code — insertion sort does the same job with fewer moves. Bubble sort is worth knowing because it's the easiest sort to explain, its one pass moves the largest to the end idea shows up in other questions, and interviewers sometimes ask you to write it and spot its early-exit optimisation.