Sorting Algorithms

Table of Contents

Introduction

In computer science a sorting algorithm is an algorithm that puts elements of a list in a certain order. We could say we want to sort it in one of two ways: ascending or descending.

[0, 1, 2, 4, 5] // Ascending order!
[5, 4, 2, 1, 0] // Descending order!

Below each title you will find the complexity. They are there for future reference only.

Bubble Sort

Complexity: Time: O(n²), Space: O(1)

Compares an element to its neighbor, if the element is larger that its neighbor, they swap places. The largest elements “bubble up” to the end with each pass of the loop.

Bubble Sort in action:

gif explaining bubble sort

Code sample.

Selection Sort

Complexity: Time: O(n²), Space: O(n)

Compares an element against all the elements of the array until it finds the smallest, then they swap places. Small elements get pushed to the beginning with each pass of the loop.

Selection Sort in action:

gif explaining selection sort

Code sample.

Insertion Sort

Complexity: Time: O(n²), Space: O(n)

Code sample.

Insertion Sort in action:

gif explaining insertion sort

results matching ""

    No results matching ""