Bubble sort, sometimes referred to as sinking sort, is a simple 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 the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller or larger elements "bubble" to the top of the list.
function bubble( arr, n) { let isSwapped = false; for(let i = 0; i < n-1; i++) { for(let j = 0; j < n-i-1; j++) { if(arr[j] > arr[j+1]) { isSwapped = false; let temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } if(!isSwapped){ break; } } return arr; }
Best Case : Ω (n)
Average Case : θ (n^2)
Worst Case: O (n^2)
O(1)
** where n is the length of the array