search
HomeWeb Front-endJS TutorialMastering Sort Algorithm like a PRO

As we've been talking about different sorting algorithms, today we'll be learning about the selection sort algorithm. A sorting algorithm that allows for the possible minimum amount of swaps in a memory-constrained environment.

Table of Contents

  1. Introduction
  2. What is Selection Sort Algorithm?
  3. How does selection sort work?
    • Time Complexity
    • Space Complexity
  4. Implementation in JavaScript
  5. Solving LeetCode Problems
  6. Conclusion

Introduction

Selection sort is a simple yet effective sorting algorithm that works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the list and moving it to the beginning (or end) of the sorted portion. This process is repeated until the entire list is sorted. In this article, we will delve into the details of the selection sort algorithm, its implementation in JavaScript, and its applications in solving real-world problems.

Mastering Sort Algorithm like a PRO

What is Selection Sort Algorithm?

Selection Sort algorithm is an in-place comparison sorting algorithm. It divides the input list into two parts:

  1. The sorted portion at the left end
  2. The unsorted portion at the right end

The algorithm repeatedly selects the smallest element from the unsorted portion and swaps it with the leftmost unsorted element, moving the boundary between the sorted and unsorted portions one element to the right.

How does selection sort work?

Let's walk through an example using the array [64, 25, 12, 22, 11]:

  1. Initial array: [64, 25, 12, 22, 11]
  • Sorted portion: []
  • Unsorted portion: [64, 25, 12, 22, 11]
  1. First pass:
  • Find minimum in unsorted portion: 11
  • Swap 11 with first unsorted element (64)
  • Result: [11, 25, 12, 22, 64]
  • Sorted portion: [11]
  • Unsorted portion: [25, 12, 22, 64]
  1. Second pass:
  • Find minimum in unsorted portion: 12
  • Swap 12 with first unsorted element (25)
  • Result: [11, 12, 25, 22, 64]
  • Sorted portion: [11, 12]
  • Unsorted portion: [25, 22, 64]
  1. Third pass:
  • Find minimum in unsorted portion: 22
  • Swap 22 with first unsorted element (25)
  • Result: [11, 12, 22, 25, 64]
  • Sorted portion: [11, 12, 22]
  • Unsorted portion: [25, 64]
  1. Fourth pass:
  • Find minimum in unsorted portion: 25
  • 25 is already in the correct position
  • Result: [11, 12, 22, 25, 64]
  • Sorted portion: [11, 12, 22, 25]
  • Unsorted portion: [64]
  1. Final pass:
    • Only one element left, it's automatically in the correct position
    • Final result: [11, 12, 22, 25, 64]

The array is now fully sorted.

Time Complexity

Selection Sort has a time complexity of O(n^2) in all cases (best, average, and worst), where n is the number of elements in the array. This is because:

  • The outer loop runs n-1 times
  • For each iteration of the outer loop, the inner loop runs n-i-1 times (where i is the current iteration of the outer loop)

This results in approximately (n^2)/2 comparisons and n swaps, which simplifies to O(n^2).

Due to this quadratic time complexity, Selection Sort is not efficient for large datasets. However, its simplicity and the fact that it makes the minimum possible number of swaps can make it useful in certain situations, especially when auxiliary memory is limited.

Space Complexity

Selection Sort has a space complexity of O(1) because it sorts the array in-place. It only requires a constant amount of additional memory space regardless of the input size. This makes it memory-efficient, which can be advantageous in memory-constrained environments.

Implementation in JavaScript

Here's a JavaScript implementation of Selection Sort Algorithm:

function selectionSort(arr) {
  const n = arr.length;

  for (let i = 0; i 


<p>Let's break down the code:</p><ol>
<li>We define a function selectionSort that takes an array as input.</li>
<li>We iterate through the array with the outer loop (i), which represents the boundary between the sorted and unsorted portions.</li>
<li>For each iteration, we assume the first unsorted element is the minimum and store its index.</li>
<li>We then use an inner loop (j) to find the actual minimum element in the unsorted portion.</li>
<li>If we find a smaller element, we update minIndex.</li>
<li>After finding the minimum, we swap it with the first unsorted element if necessary.</li>
<li>We repeat this process until the entire array is sorted.</li>
</ol>
<h2>
  
  
  Solving LeetCode Problems
</h2>

<p>Let'solve one leetcode algorithm problem using selection sort algorithm. Shall we?</p>
<h2>
  
  
  Problem: Sort An Array [Medium]
</h2>

<p><strong>Problem:</strong> Given an array of integers nums, sort the array in ascending order and return it. You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible.</p>

<p><strong>Approach:</strong>: To solve this problem, we can directly apply the Selection Sort algorithm. This involves iterating through the array, finding the smallest element in the unsorted portion, and swapping it with the first unsorted element. We repeat this process until the entire array is sorted.</p>

<p><strong>Solution:</strong><br>
</p>
<pre class="brush:php;toolbar:false">function selectionSort(arr) {
  const n = arr.length;

  for (let i = 0; i 


<p>This solution directly applies the Selection Sort algorithm we implemented earlier. While it correctly solves the problem, it's worth noting that this solution may exceed the time limit for large inputs on LeetCode due to the O(n^2) time complexity of Selection Sort. The image below shows that the solution is correct but not efficient.</p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172929732883611.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Mastering Sort Algorithm like a PRO"></p>
<h2>
  
  
  Conclusion
</h2>

<p>In conclusion, Selection Sort is a simple and intuitive sorting algorithm that serves as an excellent introduction to the world of sorting techniques. Its simplicity makes it easy to understand and implement, making it a valuable learning tool for beginners. However, due to its quadratic time complexity O(n^2), it is not efficient for large datasets. For larger datasets or performance-critical applications, more efficient algorithms like QuickSort, MergeSort, or built-in sorting functions are preferred.</p>

<hr>

<hr>
<h2>
  
  
  Stay Updated and Connected
</h2>

<p>To ensure you don't miss any part of this series and to connect with me for more in-depth<br>
discussions on Software Development (Web, Server, Mobile or Scraping / Automation), data<br>
structures and algorithms, and other exciting tech topics, follow me on:</p><div class="ltag__user ltag__user__id__878458" style="border-color:#2733b6;box-shadow: 3px 3px 0px #2733b6;">
    
      <div class="ltag__user__pic">
        <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172929732962339.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Mastering Sort Algorithm like a PRO">
      </div>
    
  <div class="ltag__user__content">
    <h2>
The Great SoluTion ?<button name="button" type="button" data-info='{"className":"User","style":"full","id":878458,"name":"The Great SoluTion ?"}' class="crayons-btn follow-action-button whitespace-nowrap c-btn--secondary fs-base follow-user" aria-label="Follow user: The Great SoluTion ?" aria-pressed="false">Follow</button>
</h2>
    <div class="ltag__user__summary">
      Software Engineer | Technical Writer | Backend, Web & Mobile Developer ? | Passionate about crafting efficient and scalable software solutions. #letsconnect ?
    </div>
  </div>
</div>



  • GitHub
  • Linkedin
  • X (Twitter)

Stay tuned and happy coding ?‍??

The above is the detailed content of Mastering Sort Algorithm like a PRO. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!