btholt / four-semesters-of-cs

https://frontendmasters.com/courses/computer-science/
668 stars 224 forks source link

Bubble sort algorithm optimization #32

Open maulikfojdar opened 4 years ago

maulikfojdar commented 4 years ago

Hi Brian, loved your courses on Frontend masters. I was looking at the solution you provided for bubble sort. While it looks good and readable, I feel the solution bubbles the largest element to the end but considers all the elements in every loop instead of leaving the bubbled elements which is kind of the purpose of bubble sort. We can reduce the time by half if we ignore the bubbled elements.

I have modified your solution by adding an index that is maintained to ignore the bubbled elements.

const bubbleSort = nums => {
  let swapped = false;
  let index = 0;

  do {
    swapped = false;
    for (let i = 0; i < nums.length - index; i++) {
      if (nums[i] > nums[i+1]) {
        let temp = nums[i];
        nums[i] = nums[i+1];
        nums[i+1] = temp;
    swapped = true;
      }
    }
    index++;
 } while(swapped)
 console.log(nums);
};