BubbleSort.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* Bubble Sort is an algorithm to sort an array. It
  2. * compares adjacent element and swaps their position
  3. * The big O on bubble sort in worst and best case is O(N^2).
  4. * Not efficient.
  5. * Somehow if the array is sorted or nearly sorted then we can optimize bubble sort by adding a flag.
  6. *
  7. * In bubble sort, we keep iterating while something was swapped in
  8. * the previous inner-loop iteration. By swapped I mean, in the
  9. * inner loop iteration, we check each number if the number proceeding
  10. * it is greater than itself, if so we swap them.
  11. *
  12. * Wikipedia: https://en.wikipedia.org/wiki/Bubble_sort
  13. * Animated Visual: https://www.toptal.com/developers/sorting-algorithms/bubble-sort
  14. */
  15. /**
  16. * Using 2 for loops.
  17. */
  18. export function bubbleSort(items) {
  19. const length = items.length
  20. let noSwaps
  21. for (let i = length; i > 0; i--) {
  22. // flag for optimization
  23. noSwaps = true
  24. // Number of passes
  25. for (let j = 0; j < i - 1; j++) {
  26. // Compare the adjacent positions
  27. if (items[j] > items[j + 1]) {
  28. // Swap the numbers
  29. ;[items[j], items[j + 1]] = [items[j + 1], items[j]]
  30. noSwaps = false
  31. }
  32. }
  33. if (noSwaps) {
  34. break
  35. }
  36. }
  37. return items
  38. }
  39. /**
  40. * Using a while loop and a for loop.
  41. */
  42. export function alternativeBubbleSort(arr) {
  43. let swapped = true
  44. while (swapped) {
  45. swapped = false
  46. for (let i = 0; i < arr.length - 1; i++) {
  47. if (arr[i] > arr[i + 1]) {
  48. ;[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]]
  49. swapped = true
  50. }
  51. }
  52. }
  53. return arr
  54. }