惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

K
Kaspersky official blog
小众软件
小众软件
Engineering at Meta
Engineering at Meta
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
V2EX
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Check Point Blog
aimingoo的专栏
aimingoo的专栏
罗磊的独立博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
MongoDB | Blog
MongoDB | Blog
L
LINUX DO - 热门话题
酷 壳 – CoolShell
酷 壳 – CoolShell
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
Martin Fowler
Martin Fowler
G
GRAHAM CLULEY
Simon Willison's Weblog
Simon Willison's Weblog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Vulnerabilities – Threatpost
云风的 BLOG
云风的 BLOG
博客园_首页
C
Cybersecurity and Infrastructure Security Agency CISA
量子位
Stack Overflow Blog
Stack Overflow Blog
Recent Announcements
Recent Announcements
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
I
Intezer
Scott Helme
Scott Helme
A
About on SuperTechFans
博客园 - 司徒正美
Hacker News: Ask HN
Hacker News: Ask HN
The GitHub Blog
The GitHub Blog
Forbes - Security
Forbes - Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Spread Privacy
Spread Privacy
T
Tailwind CSS Blog
S
Security Affairs
宝玉的分享
宝玉的分享

KIRUPA | Designers and Developers Unite

Understanding Merkle Trees Is a CompSci Degree Still Valuable in the Age of AI? The Model Context Protocol (MCP) Explained Vibe Coding + Expertise = Mega Win! 🏆 Animating our Grid How to Count in Negabinary (Base (-2)) — A Visual Guide Counting in Binary and Hexadecimal Pascal Pixel on Design, Development, and Solopreneurship! Do we really need to know how things work? 🧠 Drawing Sharp Lines on the Canvas The KIRUPA Tech Stack : It Bloom Filter: A Deep Dive Hash Functions Deep Dive Advanced Glitch Effect with Sound AI Killed the Content Creator...Star 🤩 Measuring the Distance Between Two Points by using the Pythagorean Theorem Detecting Browser Zoom Changes in JavaScript Creating a Fullscreen Grid Drawing a Perfect Grid on the Canvas Preserving the Pixel Art Look in Web Content Ensuring our Canvas Looks Good on Retina/High-DPI Screens Finding Prime Numbers Using a Sieve of Eratosthenes Two-Dimensional (2D) Arrays in JavaScript Two-Dimensional (2D) Arrays in JavaScript Animations: From Biology to JavaScript! 🦠 You’ll Always be Building & Designing Creating a Cluster Growth Animation: From Biology to JavaScript Timsort: A Lightning Fast Hybrid Sorting Algorithm Merge Sort: A Simple Step-by-Step Walkthrough 😀 - YouTube Bubble Sort: A Detailed Deep-Dive 🛁 Insertion Sort: A Deep Dive! 🍣 Selection Sort: A Step-by-Step Guide 💬 Radix Sort: A Complete Guide to Fast and Efficient Sorting! ⚡️ Career Growth Secrets Counting Sort : A Friendly (yet Detailed!) Deep Dive! 🎯 Bogosort: Sorting in the Slow Lane! 🐢 Pulling Off a Successful Redesign Creating Your Own Perfect Timing Radix Sort Making Counting Sort Work with Negative Values Diving Deep into Array Index Positions The Career Three Body Problem Counting Sort Work on Problems You Deeply Care About The Importance of Finding a Career Mentor Creating a Random Walk Simulation What is Product Strategy? Thinking about an 8K Resolution Future! 📺 Creating an Animated 3D Starfield Effect Meet the Default Sorting Algorithms! Bogosort Remapping Values Getting Started with Learning Data Structures and Algorithms Tech Slowdown Explained, Part 1: Interest Rates 💸 Easily Draw any Polygon Changing Colors in an SVG Element Using CSS and JavaScript Creating a Scrollable DIV Area Realistic CSS Animations and the linear() Timing Function! 🍱 Visualizing Recursion with the Sierpinski Triangle Fast Sorting with Quicksort The Monty Hall Problem Stacks in JavaScript Depth-First Search (DFS) and Breadth-First Search (BFS) Introduction to the Graph Data Structure Big-O Notation and Complexity Analysis Introduction to Data Structures Arrays: A Data Structure Deep Dive Hashtables: A Deep Dive into Efficient Data Storage and Retrieval Trie (aka Prefix Tree) Embracing Generative AI with Open Arms! 🧸 Impact of AI on UI/UX Design with Chloe Barreau 🎨 Heap Data Structure Binary Search Trees Binary Tree Traversal Alphabetically Sort Names in an Array Overlapping Elements on Top of Each Other Developer Relations and Beyond with Jamie Barton! 🚀 A Trip Down Memory Lane 💾 Binary Trees Linked List The Present and Future of AI Tools with Ray (aka devbyrayray) "Guess the Number" and Binary Searching! 🔍 Switching Web Hosts in 2023 😱 SVG: Converting Shape to Path The Versatility of SVGs 🌀 Spinning Circular Text Introduction to Trees Faster Searching with Binary Search Search Algorithms and Linear Search Fibonacci and Going Beyond Recursion Guess the Number Game
Stability and Sorting Algorithms
Kirupa Chinnathambi · 2023-10-05 · via KIRUPA | Designers and Developers Unite

There are many (totally work-safe!) words people use to describe sorting algorithms. One such word is stability. Some sorting algorithms are stable, and some sorting algorithms are far from it. In this short tutorial, we'll explain what stability in the context of sorting algorithms means and walk through an example.

Onwards!

Stability refers to a property that some sorting algorithms have where the relative order of equal elements in the sorted output is the same as their relative order in the original unsorted input. This may be a bit convoluted, so let's simplify this with an example. In our example, we start off with an unsorted list of values made up of a person's name and age:

What we want to do is sort our list based on age, starting with the lowest value at the top. Notice that two items in our list have the same value. Both Alice and Michael are 22 years old. In a stable sorting algorithm, when we perform our sort, the order of Alice and Michael will remain the same as what they are in their current unsorted list:

In other words, our unsorted list had Alice appearing before Michael. In our sorted list, Alice continues to appear before Michael. Stability achieved:

If we had instead used an unstable algorithm, we would have seen an outcome similar to the following:

In this case, the relative order of Alice and Michael has changed compared to the original input. This is an example of an unstable sorting algorithm. Even though Alice and Michael are the same age, their order in the sorted output is not guaranteed to match their order in the input.

Sorting Algorithm Stability Showdown

Which sorting algorithms make the cut on the stability front? Take a look at the following table and the more detailed explanation below for the answer:

Sorting Algorithm Stability
Bubble Sort Stable
Selection Sort Unstable
Insertion Sort Stable
Merge Sort Stable
Quick Sort Unstable
Heap Sort Unstable
Counting Sort Stable
Radix Sort Stable
Tim Sort (a hybrid) Stable

More detailed explanation:

  1. Bubble Sort: Bubble Sort is a stable sorting algorithm. It compares adjacent elements and swaps them if they are out of order, but it does not change the relative order of equal elements.

  2. Selection Sort: Selection Sort is an unstable sorting algorithm. It repeatedly selects the minimum element and places it at the beginning of the sorted portion, which may change the relative order of equal elements.

  3. Insertion Sort: Insertion Sort is a stable sorting algorithm. It builds the sorted portion of the array one element at a time, preserving the relative order of equal elements.

  4. Merge Sort: Merge Sort is a stable sorting algorithm. It divides the array into smaller parts, sorts them, and then merges them back together while maintaining the relative order of equal elements.

  5. Quick Sort: Quick Sort is generally considered unstable. It involves partitioning the array based on a chosen pivot, and the pivot's choice can affect the relative order of equal elements.

  6. Heap Sort: Heap Sort is usually considered unstable. It uses a binary heap data structure to sort elements and may change the order of equal elements.

  7. Counting Sort: Counting Sort is a stable sorting algorithm. It counts the occurrences of each element and then reconstructs the sorted order, maintaining the relative order of equal elements.

  8. Radix Sort: Radix Sort is a stable sorting algorithm. It sorts elements by considering their digits in a specific radix (base), preserving the relative order of equal elements.

  9. Tim Sort: Tim Sort is a hybrid sorting algorithm based on Merge Sort and Insertion Sort. It is designed to be stable, and it uses various techniques to ensure stability in sorting.

One thing to note is that, while these characteristics are generally true for these sorting algorithms, some specific implementations may deviate a bit. It's best to double-check the implementation.

For the sorting algorithm implementations you encounter on this site, though, the stability table is totally accurate!

Conclusion

In far too many situations, the stability of a sorting algorithm can be crucial. It may seem unnecessary when we look at an example of some age values being sorted, but imagine sorting a list of values whose initial order is critical as part of managing a queue. Any changes in the order can have negative consequences. This is especially multiplied if our data goes through multiple rounds of sorting. A combination of sort (and maybe even merge!) operations involving stable and unstable sorting algorithms will reduce the predictability of the final output. None of these are great.

Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.

Your support keeps this site going! 😇

Kirupa's signature!