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

推荐订阅源

Martin Fowler
Martin Fowler
L
LINUX DO - 最新话题
P
Proofpoint News Feed
Cyberwarzone
Cyberwarzone
Know Your Adversary
Know Your Adversary
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
Lohrmann on Cybersecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Security Latest
Security Latest
T
The Exploit Database - CXSecurity.com
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy & Cybersecurity Law Blog
K
Kaspersky official blog
The Last Watchdog
The Last Watchdog
Webroot Blog
Webroot Blog
Scott Helme
Scott Helme
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
WordPress大学
WordPress大学
L
LINUX DO - 热门话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Visual Studio Blog
O
OpenAI News
AI
AI
Hacker News: Ask HN
Hacker News: Ask HN
V2EX - 技术
V2EX - 技术
GbyAI
GbyAI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Simon Willison's Weblog
Simon Willison's Weblog
S
Schneier on Security
Spread Privacy
Spread Privacy
Y
Y Combinator Blog
I
InfoQ
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
F
Fortinet All Blogs
C
CERT Recently Published Vulnerability Notes
T
The Blog of Author Tim Ferriss
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
N
News and Events Feed by Topic
Project Zero
Project Zero
小众软件
小众软件
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
B
Blog
G
Google Developers Blog

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! 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 Stability and Sorting Algorithms 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
Bogosort
Kirupa Chinnathambi · 2024-01-24 · via KIRUPA | Designers and Developers Unite

Let's explore the whimsical world of Bogosort, a sorting algorithm known for its sheer inefficiency and randomness!

We’ve looked at a variety of sorting algorithms so far, and most of them have been quite good. Some, like Mergesort and Quicksort, have been extra good with nice performance and memory usage. Today, we are going to take a detour and learn about a horribly inefficient algorithm known as Bogosort (aka permutation sort, stupid sort, or monkey sort).

The reason we are learning about this algorithm is not to apply it towards any practical real-world implementation. Nope. We spend so much time learning how to make our algorithms run as fast as possible, so let us do the exact opposite with Bogosort. Also, Bogosort is commonly referenced in memes and pop-culture moments, so learning about Bogosort will also help you to stay “in the loop” with the cool kids.

Onwards!

How Bogosort “Works”

If we had a monkey, how long would it take for it to randomly hit keys on a keyboard and end up writing a complete work from Shakespeare?

This question has intrigued people for a long time, and the discussion and answer around this is known as the infinite monkey theorem. The general idea (and answer) is as follows: if you give a monkey an infinite amount of time to randomly hit keys on the keyboard, it can create any written work.

Hard to believe? Well, an important detail to call out is that the monkey has no idea what it is doing. It just keeps randomly hitting keys on the keyboard:

Because there is an infinite amount of time, at some point in the likely very distant future, random keys would have been hit in just the right order to create words, sentences, chapters, and maybe even something that is Shakespearian:

Now, let’s get back to the topic at hand. Our friendly Bogosort algorithm sorts numbers in a way similar to how our curious monkey writes books. Let’s say that our input is the following array of numbers:

Bogosort would sort these numbers using the following steps:

  1. Shuffle: Take the input array (or list) of elements and randomly shuffle them
  2. Check: Check if the shuffled array is now magically in a sorted order
  3. Repeat: If the list is not sorted, go back to step 1 and repeat the process

Notice that the only logic for sorting our items is in Step 1, where all of the items are randomly shuffled. This means that, at each step, there is no logical or deterministic way to figure out what the array will look like. Step 1, run multiple times on the same input, would likely result in the random arrangement of numbers being different each and every time. This is a huge departure from every other search algorithm we have looked at where there was a strategy involved that didn’t involve randomly shuffling the entire input.

This is why going deeper and looking at what Bogosort does at each iteration isn’t particularly helpful. Each iteration will have a completely random arrangement of our input numbers:

The only thing we know with certainty is that all of the items will eventually be shuffled in a way where they end up being sorted. The thing we don’t know is how long that will take. It could be done quickly or it could take forever! Because of this unpredictability, Bogosort isn’t meant to be used in any real-world scenario outside of comical academic exercises.

Performance Characteristics

As you probably figured out by now, Bogosort is terribly inefficient. The running time of Bogosort is highly unpredictable and has horrendous time complexity, but let’s break that down further.

Best Case

If, by pure luck, the input array happens to be already sorted, Bogosort will recognize this in a single check and exit immediately. In this (extremely rare) scenario, the best-case time complexity is O(n), where the only work is to check each item and ensure it is already sorted.

Average Case

The average case time complexity of Bogosort is O(n!). This stems from the fact that, on average, it will take n! (n factorial) random shuffles to stumble upon the correct sorted permutation. Factorial growth is incredibly fast...which means our algorithm will run incredibly slow:

Even for moderate-sized lists, the average runtime becomes nearly infinite. For example, if we had to sort just 10 numbers, the number of steps in 10! is already over 3.62 million.

Worst Case

Technically, the worst-case scenario for Bogosort is infinite. There is no upper bound on the number of shuffles it might take. The universe might end before Bogosort accidentally sorts our data!

JavaScript Implementation

Before we wrap things up, here is a brief JavaScript implementation of Bogosort:

let iterations = 0;

function isSorted(arr) {
  // Checks if the given array is sorted
  for (let i = 0; i < arr.length - 1; i++) {
    if (arr[i] > arr[i + 1]) {
      return false; // Not sorted
    }
  }
  return true; // Sorted
}

function shuffle(arr) {
  // Shuffles the array (in place) using Fisher-Yates algorithm
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
}

function bogosort(arr) {
  iterations = 0;

  // Keep shuffling until the array is magically sorted
  while (!isSorted(arr)) {
    iterations++;
    shuffle(arr);
  }
  return arr;
}

// Example usage:
const myArray = [5, 3, 1, 8, 2, 0];
console.log(`Unsorted array: ${myArray}`);

const sortedArray = bogosort(myArray);
console.log(`Sorted array: ${sortedArray}`); 

console.log(`Sorting took ${iterations} iterations!`);

If you run this code, pay attention to the number of iterations that it will take to properly sort our small six-item array:


While the results will vary wildly, notice that our code ran over 1800 times...just for 6 items! This is further proof that Bogosort isn’t meant to be put anywhere close to actual production code.

Conclusion

Bogosort, due to its reliance on random chance, is not a practical sorting algorithm by any means. Its primary value lies in being a warning sign to illustrate the stark contrast between a terribly inefficient algorithm and a well-designed sorting algorithm like Merge Sort, Quicksort, or others with typical time complexities in the O (n log n) range. Also, whatever you do, never look in the mirror and say Bogosort three times.

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!