Skip to main content

Command Palette

Search for a command to run...

JavaScript Algorithms #2 - Selection Sort

Updated

1. What is Selection Sort?

Selection sort is pretty much similar to the bubble sort, but instead of first placing large values into sorted position, selection sort places small values first into the sorted position. So starting from the first element, store it inside a variable and compare its value with the second element. If the second one is smaller, replace the value of variable with the value of second element. And so on, we compare the value of the variable with every element in the array. After the first iteration, we know we have the smallest element in the variable. Swap it with the lowest index element and we have the smallest element in the very front of the element. Repeat this process and iterate through the entire array.

2. Selection Sort Pseudo Code

  1. Start the outer loop. We will stop the iteration before it hits the array.length - 1 because once we compare the second last element of the array with the final one, everything will be already sorted.
  2. Declare a variable called 'minIndex' to store the index of the smallest value we've seen so far. Let's just assume the first element is the smallest value and store it's index in the 'minIndex' for now.
  3. Start the inner loop with the element[i+1]. Since the element[i] will be the standard element that we compare with the next ones, we can start the inner loop iteration with the element[i+1].
  4. If a smaller number is found while the iteration, designate the index of that element to be the new minimum and continue until the end of the array.
  5. If the value of 'minIndex' is not the index you initially began with, it means new minimum has been found. Swap the two values.
  6. Repeat this with the next element until the array is sorted.

    3. Implementing the Selection Sort

function selectionSort(array){
               for(let i = 0; i < array.length - 1; i++){
                   let minIndex = i;
                   for(let j = i + 1; j < array.length; j++){
                       if(array[j] < array[minIndex]){
                           minIndex = j;
                       }
                   }

                   if(minIndex !== i){
                       [array[i], array[minIndex]] = [array[minIndex], array[i]]; //let temp = array[i]; array[i] = array[minIndex]; array[minIndex] = temp;
                   }
               }
               return array;
           }

4. Time Complexity of the Selection Sort

The selection sort iterate through the array twice with its outer loop and inner loop, so even in the best case scenario where the array is almost sorted or already sorted and we don't need to swap, it still have quadratic time complexity just by the comparison process. In the worst case scenario, it'll take O(n²) for the comparison and O(n) for the swaps. But still, it has O(n²) of time complexity because according to the Big O notation, O(n²) has the largest contribution and O(n) can be ignored.

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