When it comes to sorting algorithms, Bubble Sort is usually the first that comes to mind. Though it might not be the fastest tool in the shed, it's definitely straightforward to implement and is often the first sorting method new programmers think of when trying to implement a sorting method on their own.
Here's how it works: we go through each element in our vector and check to see if it is larger than the element to it's right.
If it is, we swap the elements and then move to the next element.
In this way, we sweep through the array
{% method %} {% sample lang="jl" %} import:1-10, lang:"julia" {% sample lang="cs" %} import:9-27, lang:"csharp" {% sample lang="c" %} import:10-20, lang:"c_cpp" {% sample lang="java" %} import:2-12, lang:"java" {% sample lang="js" %} import:1-11, lang:"javascript" {% sample lang="py" %} import:4-9, lang:"python" {% sample lang="m" %} import:11-23, lang:"matlab" {% sample lang="hs" %} import, lang:"haskell" {% sample lang="cpp" %} import:13-23, lang:"c_cpp" {% sample lang="rs" %} import:6-16, lang:"rust" {% sample lang="d" %} import:3-18, lang:"d" {% sample lang="go" %} import:7-21, lang:"golang" {% sample lang="racket" %} import:6-19, lang:"racket" {% sample lang="swift" %} import:1-13, lang:"swift" {% sample lang="ti83b" %} import:2-13, lang:"ti-83_basic" {% sample lang="ruby" %} import:3-13, lang:"ruby" {% sample lang="crystal" %} import:1-11, lang:"crystal" {% sample lang="php" %} import:3-15, lang:"php" {% endmethod %}
... And that's it for the simplest bubble sort method. Now, as you might imagine, computer scientists have optimized this to the fiery lakes of Michigan and back, so we'll come back to this in the future and talk about how to optimize it. For now, it's fine to just bask in the simplicity that is bubble sort. Trust me, there are plenty of more complicated algorithms that do precisely the same thing, only much, much better (for most cases).
{% method %} {% sample lang="jl" %} import, lang:"julia" {% sample lang="cs" %} BubbleSort.cs import, lang:"csharp" Program.cs import, lang:"csharp" {% sample lang="c" %} import, lang:"c_cpp" {% sample lang="java" %} import, lang:"java" {% sample lang="js" %} import, lang:"javascript" {% sample lang="py" %} import, lang:"python" {% sample lang="m" %} import, lang:"matlab" {% sample lang="hs" %} import, lang:"haskell" {% sample lang="cpp" %} import, lang:"c_cpp" {% sample lang="rs" %} import, lang:"rust" {% sample lang="d" %} import, lang:"d" {% sample lang="go" %} import, lang:"golang" {% sample lang="racket" %} import, lang:"racket" {% sample lang="swift" %} import, lang:"swift" {% sample lang="ti83b" %} import, lang:"ti-83_basic" {% sample lang="ruby" %} import, lang:ruby" {% sample lang="crystal" %} import, lang:"crystal" {% sample lang="php" %} import, lang:"php" {% endmethod %}
<script> MathJax.Hub.Queue(["Typeset",MathJax.Hub]); </script>