Skip to main content

Command Palette

Search for a command to run...

JavaScript Algorithms #1- Bubble Sort

Updated

1. What is Sorting?

Sorting is the process of rearranging the elements in a data structure(e.g. array) so that the elements are in order. JavaScript offers a built-in method Array.prototype.sort() which allows us to sort the elements of an array easily. The sort() method returns the sorted array in alphabetical and ascending order. However, while it works well with the string, sorting numbers with this method can produce incorrect results as sort() method converts every type of elements into strings and then compare their sequences of UTF-16 code unit values for sorting. We could use a compare function to fix this but there are many other efficient ways to sort the data. Bubble sort is one of those.

2. What is Bubble Sort?

Bubble sort is a sorting algorithm where the largest values bubble up to the top. Bubble sort compares two adjacent elements and swaps them until they are not in the intended order, so each element of the array moves to the end in each iteration just like the bubbles in a glass rise up to the surface.

3. Bubble Sort Pseudo Code

  1. Start looping the array with a variable called i.
  2. Start an inner loop from the beginning until (array.length - 1 - i) with a variable j. We don't have to iterate until the end because when the j reaches the final element, it doesn't have the right(next) element to compare with(therefore (array.length - 1)). Also, we should minus i from the (array.length - 1), because after the each iteration of i, the number of i elements will be locked at the end. We don't have to do anything with the already sorted elements.
  3. If array[j] is greater than array[j+1], swap those two values.
  4. Return the sorted array.

    4. Implementing the Bubble Sort

function bubbleSort(array){
               const arr = array.slice(); //making a shallow copy of array using slice() method to make it a pure function(so that it doesn't affect the original array)

               for (let i = 0; i < arr.length; i++){
                   for (let j = 0; j < arr.length - 1 - i; j++){
                       if (arr[j] > arr[j+1]){
                         [arr[j], arr[j+1]] = [arr[j+1], arr[j]]; //let temp = array[j]; array[j] = array[j+1]; array[j+1] = temp
                       }
                   }
               }
               return arr;
           }

5. Optimizing the Code

To make the bubble sort more efficient, we need a new variable. This variable will tell us whether the swap has occurred. If the swap hasn't occurred, we'll just break out of the loop because no swap means the array has already been sorted properly. Let's call this variable 'noSwap' and make its default value 'true'. If the swap happens, change its value to 'false'. If the value of 'noSwap' is true after the iteration, just break out of the loop.

function bubbleSort(array){
               const arr = array.slice()
               let noSwaps; 
               for (let i = 0; i < arr.length; i++){
                   noSwaps = true;
                   for (let j = 0; j < arr.length - 1 - i; j++){
                       if (arr[j] > arr[j+1]){
                         [arr[j], arr[j+1]] = [arr[j+1], arr[j]];
                         noSwaps = false;
                       }
                   }
                   if (noSwaps) break; //if (noSwaps === true) break;
               }
               return arr;
           }

6. Time Complexity of the Bubble Sort

In the worst case scenario, the complexity of bubble sort will be O(n²) because we have nested loop. But in the best case scenario or using our optimized version, it could be more like a linear search O(n).

More from this blog

[Kream 클론 프로젝트] 상품 더보기 기능

목표 offset/limit parameter를 사용한 상품 더보기 기능 구현 과정 1. 상품 더보기 기능 상품 목록 하단의 더보기 버튼을 누를 때마다 상품을 8개씩 더 로딩해오는 기능을 구현하기위해 예전에 배웠던 query parameter와 offset/limit 개념을 활용했다. offset과 limit을 설정해두면 데이터 요청 후 받아온 결과값에 순서를 부여해서 offset부터 limit까지의 데이터만 보여줄 수 있도록 페이징 처리...

Jul 22, 2022

[Kream 클론 프로젝트] 상품 검색 & 정렬 기능

목표 상품의 검색과 옵션별 정렬이 가능한 상품 목록 페이지 구현 과정 1. 상품 목록(메인) 페이지 UI 1) Kream이 상품 거래 사이트이다보니 각 상품마다 동일하게 반복되는 양식들이 많았는데, 이 부분들을 전부 컴포넌트로 만들고 재사용함으로써 코드의 길이를 많이 줄일 수 있었다. 특히 2차 프로젝트에서는 styled components를 사용하면서 각 페이지마다 js파일의 코드 양이 두배로 많아지는 바람에 한번 작성하고나면 알아보기가...

Jul 22, 2022

[Lululemon 클론 프로젝트] 장바구니 페이지

목표 상품 추가 / 삭제 / 수량 변경이 가능한 장바구니 페이지 구현 과정 1. 상품 데이터 받아오기 1) 사용자가 장바구니에 넣은 상품들의 목록을 렌더링하기위해 fetch 함수로 서버에서 데이터를 받아온 후 'itemList' 변수에 저장해두었다 . 2) 사용자를 식별한 다음 그에 맞는 데이터를 불러와야하기때문에 request header에 로그인시 발급했던 토큰 인가 과정을 추가했다. 코드🔻 const Bag = () => { co...

Jun 11, 2022

[Lululemon 클론 프로젝트] 로그인/회원가입 페이지

목표 JWT 인증방식을 활용한 로그인/회원가입 페이지 구현 과정 1. 로그인/회원가입 페이지 UI 1) lululemon의 사이트는 로그인 페이지에서 회원가입 버튼 클릭시 양식이 슬라이드로 올라와 한 페이지에서 로그인과 회원가입을 모두 진행할 수 있는 방식으로 되어 있었다. 이를 구현하기 위해 로그인 양식과 회원가입 양식을 각각 컴포넌트로 만든 뒤 'modal' 변수의 상태값이 true인지 false인지에 따라 적절한 컴포넌트가 렌더링될 수 ...

Jun 11, 2022

Rey's Blog

49 posts