JavaScript Data Structure and Algorithm - Detailed Explanation of Sorting

Bubble Sort

principle

Bubble sort compares all adjacent two items and swaps them if the first is greater than the second.

code one

/**
 * 冒泡排序(升序)
 * @param {*} array 
 * @returns 
 */
function bubbleSort(array) {
    
    
    const {
    
     length } = array
    for (let i = 0; i < length; i++) {
    
    
        for (let j = 0; j < length; j++) {
    
    
            if (array[j] > array[j + 1]) {
    
    
                let temp = array[j + 1]
                array[j + 1] = array[j]
                array[j] = temp
            }
        }
    }
    return array
}

Optimizing Bubble Sort

code two

selection sort

principle

The general idea of ​​selection sort is to find the smallest value in the data structure and place it first, then find the second smallest value and place it second.

TS code

function selectionSort(array: Array<number>) {
    
    
    const {
    
     length } = array
    for (let i = 0; i < length; i++) {
    
    
        let IndexMin = i
        for (let j = i; j < length; j++) {
    
    
            if (array[IndexMin] > array[j]) {
    
    
                console.log(j);
                IndexMin = j
            }
        }
        if (i != IndexMin) {
    
    
            let temp = array[IndexMin]
            array[IndexMin] = array[i]
            array[i] = temp

        }
    }
    return array
}

insertion sort

JavaScript code

function insertionSort(arr) {
    
    
    for (var index = 1; index < arr.length; index++) {
    
    
        var end = index;
        var element = arr[index];
        // 比当前值大的都向前移位(前一位覆盖当前位),直到不符合要求
        while (end > 0 && element < arr[end - 1]) {
    
    
            arr[end] = arr[end - 1];
            end--;
        }
        // 把element 赋值end位
        arr[end] = element;
    }
}

This algorithm outperforms selection sort and bubble sort when sorting small arrays

merge sort

quick sort

principle

1. Select a base number so that all the numbers on the left of the base number are smaller than it, and the numbers on the right side are all larger than it.
2. (Ascending order) Set i and j to search from the left and right respectively, find the first number larger than the base from the left, find the first number smaller than the base from the right, and then exchange the two numbers. When i and j meet, exchange the value
3 at the base and i position, and then process the arrays on both sides in the same way.

JavaScript code

function QuickSort(arr, s, e) {
    
    
    if(s>=e)return
    let basicValue = arr[s]  // 基准值
    let swapIndex = s + 1   // 交换初始位
    for (let i = swapIndex; i <= e; i++) {
    
    
        if (arr[i] < basicValue) {
    
    
            // 交换
            let temp = arr[i]
            arr[i] = arr[swapIndex]
            arr[swapIndex] = temp
            swapIndex++
        }
    }
    // 交换
    let temp = arr[--swapIndex]
    arr[swapIndex] = arr[s]
    arr[s] = temp
    QuickSort(arr, s,swapIndex-1)
    QuickSort(arr,swapIndex+1,e)
}

counting sort

principle

Counting sort is a distributed sort
Counting sort uses a temporary array that stores the number of occurrences of each element in the original array. After all elements are counted
, the temporary array is sorted and iterated to build the sorted array

TS code

/**
 * 计数排序
 */
function countingSort(array: Array<number>) {
    
    
    if (array.length < 2) return array
    const maxValue = findMaxValue(array)
    // 计数数组
    const counts = new Array(maxValue + 1).fill(0)
    array.forEach(item => {
    
    
        counts[item]++
    })

    let sortIdnex = 0
    counts.forEach((count, i) => {
    
    
        while (count > 0) {
    
    
            array[sortIdnex++] = i
            count--
        }
    })
    return array
}
/**
 * 找数组中的最大值
 * @param array 
 * @returns 
 */
function findMaxValue(array: Array<number>) {
    
    
    let max = array[0]
    for (let i = 0; i < array.length; i++) {
    
    
        if (array[i] > max) {
    
    
            max = array[i]
        }
    }
    return max
}

bucket sort

principle

The algorithm is divided into two parts
1. It is used to create buckets and divide different elements into different buckets.
2. Insertion sorting algorithm for each bucket and merge all buckets into the sorted result array

TS code

/**
 * 桶排序
 * @param array 
 * @param bucketSize 
 */
function createBuckets(array: Array<number>, bucketSize: number) {
    
    
    let minValue = array[0]
    let maxValue = array[0]
    for (let i = 1; i < array.length; i++) {
    
    
        if (array[i] < minValue) {
    
    
            minValue = array[i]
        } else if (array[i] > maxValue) {
    
    
            maxValue = array[i]
        }
    }
    // 已得到到数组的最小值和最大值
    const bucketCount = Math.floor((maxValue - minValue) / 2) + 1
    const buckets: Array<Array<number>> = []    // 创建桶
    for (let i = 0; i < bucketCount; i++) {
    
    
        buckets[i] = []
    }
    // 放入各自的桶中
    for (let i = 0; i < array.length; i++) {
    
    
        const buketIndex = Math.floor((array[i] - minValue) / bucketSize)
        buckets[buketIndex].push(array[i])
    }
    return buckets
}
/**
 * 排序每个桶并合并每个桶
 * @param buckets 
 * @returns 
 */
function sortBuckets(buckets: Array<Array<number>>) {
    
    
    const sortedArray = []
    for (let i = 0; i < buckets.length; i++) {
    
    
        if (buckets[i] != null) {
    
    
            // 插入排序对每个桶进行(这个是上面的插入排序insertionSort)排序
            insertionSort(buckets[i]);
            // 合并桶
            sortedArray.push(buckets)
        }
    }
    return sortedArray
}

radix sort

principle

Cardinality sorting is also a distributed algorithm that divides integers into buckets according to the effective bits or bases of the array.
For base 10 numbers, base 10 is used. Therefore, the algorithm will use 10 buckets to distribute the elements and sort based on the ones digit, then tens, then hundreds and so on.

TS code

function radixSort(arr: Array<number>) {
    
    
    let length = arr.length
    let counter: Array<Array<number>> = []
    let mod = 10
    let dev = 1
    if (length < 1) {
    
    
        return arr
    }
    // 获取数组中最大位数
    let maxDigit = String(Math.max(...arr)).length
    for (let i = 0; i < maxDigit; i++, dev *= 10) {
    
    
        for (let j = 0; j < arr.length; j++) {
    
    
            // 获取相应位置上的数
            var bucket = (arr[j] / dev) % mod;

            if (counter[bucket] == null) {
    
    
                counter[bucket] = [];
            }
            counter[bucket].push(arr[j]);
        }
        console.log(counter);
        
        var pos = 0;
        console.log(counter.length);
        
        for (let k = 0; k < counter.length; k++) {
    
    
            var value = null;
            if (counter[k]) {
    
    
                while ((value = counter[k].shift()) != null) {
    
    
                    arr[pos++] = value;
                }
            }
        }    
    }
    return arr;
}

heap sort

principle

1. Use an array to create a maximum heap as source data.
2. After creating the maximum heap, the maximum value will be stored in the first position of the heap. We need to exchange this maximum value with the last node of the largest heap, and then move the length-1 of the heap
3. Move the root node down, and repeat step 2 until the end

TS code

/**
* 构建大顶堆
*/
function Heap(arr: Array<number>, length: number) {
    
    
    // 构建大顶堆
    for (let i = arr.length - 1; i >= 0; i--) {
    
    
        swap(arr, i)
    }
    // 递归交换
    function swap(arr: Array<number>, i: number) {
    
    
        let left = 2 * i + 1
        let right = 2 * i + 2
        let max: number = i
        if (left < length && arr[left] > arr[max]) {
    
    
            max = left
        }
        if (right < length && arr[right] > arr[max]) {
    
    
            max = right
        }
        if (max != i) {
    
    
            let temp = arr[max]
            arr[max] = arr[i]
            arr[i] = temp
            swap(arr, max)
        }
    }
}
function sort(arr: Array<number>) {
    
    
    Heap(arr, arr.length)
    let length = arr.length - 1
    while (length >= 0) {
    
    
        let temp = arr[0]
        arr[0] = arr[length]
        arr[length] = temp
        length--
        Heap(arr, length)
    }
    return arr
}

Guess you like

Origin blog.csdn.net/qq_45859670/article/details/123534600