kdocs
GitHub
SC - DSA
SC - DSA
  • Complexity or Asymptotic Behavior
  • Data Structures
    • Graphs
    • Trees
  • Algorithms
    • Search
    • Sort
Powered by GitBook
On this page
  • Bubble Sort
  • Selection Sort
  • Insertion Sort
  • Merge Sort
  • Quick Sort
  • Radix Sort
  • Heap Sort
  1. Algorithms

Sort

PreviousSearch

Last updated 5 months ago

Bubble Sort

Asymptotically this will be O(N2)O(N²)O(N2), since in the worst case you will go through the NNN size DS NNN times.

In practice, after each run the last element on the DS will always be the largest, so you don't have to go N∗NN*NN∗N, you end up going N→N−1→N−2→...→1N \rightarrow N-1 \rightarrow N-2 \rightarrow ... \rightarrow 1N→N−1→N−2→...→1 and having O(N(N+1)2)O(\frac{N(N+1)}{2})O(2N(N+1)​).

Implementation on Arrays

function bubbleSort(arr: number[]): void {
    for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < (arr.length - 1 - i); j++ ) {
            if (arr[j] > arr[j + 1]) {
                const tmp = arr[j];
                arr[j] = arr[j + 1];
                arr[j+1] = tmp;
            }
        }
    }
}

Selection Sort

Insertion Sort

Merge Sort

Quick Sort

After this, you take a new pivot for each of the new sections, and do it again, and on and on... until reaching the base case of a section of size 0 or 1.

It should do the sorting inplace, instead of creating temporary structures to hold these middle arrays.

Asymptotically QuickSort can be O(N logN)O(N\ log N)O(N logN) or O(N2)O(N²)O(N2) depending on how you pick your pivots.

The literal wort case scenario would be having a reverse ordered Array and picking the last element as the pivot.

Implementation on Arrays

recursive
function partition(arr: number[], lo: number, hi: number): number {
    const pivot = Math.floor((lo + hi) / 2);
    let idx = lo - 1;
    
    for (let i = lo; i < hi; i++) {
        if (arr[i] <= arr[pivot]) {
            idx++;
            const temp = arr[i];
            arr[i] = arr[idx];
            arr[idx] = temp;
        }
    }
    
    idx++;
    arr[hi] = arr[idx];
    arr[idx] = arr[pivot];
    
    return idx;
}

function quickSort(arr: number[], lo: number, hi: number): void {
    if (lo >= hi) return;
    const pivotIdx = partition(arr, lo, hi);
    
    quickSort(arr, lo, pivotIdx - 1);
    quickSort(arr, pivotIdx + 1, hi);
}

quickSort(arr, 0, arr.length - 1);

Radix Sort

Heap Sort

The simplest sorting algorithm, it's a algorithm. Basically starts at first DS position and checks if it is greater than the next one, and keeps repeating this process until it is done.

It's a algorithm. It takes a pivot value that usually is in the middle of the DS, and sorts every value smaller or equal than the pivot to it's left and every value greater to the right.

Greedy
Divide and Conquer
Sorting (Bubble, Selection, Insertion, Merge, Quick, Counting, Radix) - VisuAlgo
Drawing
Logo