JavaScript Sorting Algorithms

Posted by GregL83 on Fri, 04 Oct 2019 11:19:39 +0200

1: Basic concepts

Time complexity: The time spent on algorithm execution.

This complexity is directly related to the number of samples. The complexity reflects the performance of the algorithm. Generally speaking, the lower the complexity, the shorter the time consumed by the algorithm.

    /* O(N1) */
    for (var i = 0; i < data.length; i++) {
        ...
    }
    
    /* O(N2) */
    for (var i = 0; i < data.length; i++) {
        for (var j = 0; j < data.length; j++) {
            ...
        }
    }

Spatial complexity: The amount of memory required to run a program.

Space complexity and time complexity are opposite, for example, the higher the time complexity, the lower the space complexity; conversely, the opposite.

Internal sorting: All sorting operations are done in memory.

2: Common Sorting Algorithms

Bubble Sort

Basic concepts: Compare the two adjacent numbers in turn, put decimal in front, large number in the back.

Time complexity: O(N2).

The realization principle: repeat the sequence of rows to be sorted, compare two elements at a time, put the big elements behind, and exchange them if their order is wrong.

Code implementation: There are two layers of nested loops, the outer loop traverses each item of the array, and the inner loop is used to compare two elements, each time the inner loop is reduced by 1.

    function bubbleSort(arr) {
        var length = arr.length;
        for (var i = 0; i < length; i++) {
            for (var j = 0; j < length - 1 - i; j++) {
                if (arr[j] > arr[j+1]) {
                    [arr[j], arr[j+1]] = [arr[j+1], arr[j]];  
                }
            }
        }
        return arr;
    }

Selection Sort

Time complexity: O(N2).

Implementation principle: find the smallest (large) element stored in the sequence that is never sorted to the specified starting position, and repeat the last step in the sequence element that has never been sorted until the sorting is completed.

Code implementation: two layers of nested loop, the outer loop traverses each item of the array, the inner loop is used to find the minimum or maximum value in the sample, each time the inner loop minus 1.

    function selectionSort(arr) {
        var length = arr.length;
        var minIndex, temp;
        for (var i = 0; i < length - 1; i++) {
            minIndex = i;
            for (var j = i + 1; j < length; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            [arr[minIndex], arr[i]] = [arr[i], arr[minIndex]];
        }
        return arr;
    }

Quick Sort

Time complexity: O(N * log2N).

Implementation principle: decomposing the data into different sub sequences containing smaller elements and larger elements in a recursive way.

Code implementation: Find a number as a reference, then larger than this number on the left side of the number, smaller than it on the right side, and then do the same operation on the left and right sides of the sequence.

    function partition(arr, low, high) {
      let pivot = arr[low];
      while (low < high) {
        while (low < high && arr[high] > pivot) {
          --high;
        }
        arr[low] = arr[high];
        while (low < high && arr[low] <= pivot) {
          ++low;
        }
        arr[high] = arr[low];
      }
      arr[low] = pivot;
      return low;
    }
    function quickSort(arr, low, high) {
      if (low < high) {
        let pivot = partition(arr, low, high);
        quickSort(arr, low, pivot - 1);
        quickSort(arr, pivot + 1, high);
      }
      return arr;
    }

Insertion Sort

Time complexity: O(N2).

Implementation principle: constructing an ordered sequence, unsorted data is scanned from the back of the ordered sequence, and the correct location is inserted.

Code implementation: Two layers of nested loop to create sorted array, starting with the first element of the array, larger than this number on the left, smaller than it on the right.

    function insertSort(arr) {
        for(let i = 1; i < arr.length; i++) {
            for(let j = i; j > 0; j--) {
                if(arr[j] < arr[j-1]) {
                    [arr[j], arr[j-1]] = [arr[j-1], arr[j]];
                } else {
                    break;
                }
            }
        }
        return arr;
    }