Bubble Sort, Selection Sort, Insertion Sort, Quick Sort

Bubble Sort

(The most commonly used and the simplest sorting algorithm, but it is the least efficient among the three sorting algorithms, suitable for sorting scenarios with a small amount of data, because the bubbling principle is simple )

The time complexity is O(n*n), which can be sorted from front to back or from back to front.

Avati

Case analysis: put the largest number at the end of each round

 //冒泡排序
    let arr = [2, 4, 1, 6, 3]
    function bubbled(arr) {
        for (let i = 0; i < arr.length - 1; i++) {
            //【!!注意】这里不是j=i,因为回回都必须重头遍历,才能不漏一个,不然会有BUG
            for (let j = 0; j < arr.length - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    let temp
                    temp = arr[j]
                    arr[j] = arr[j + 1]
                    arr[j + 1] = temp
                }
            }
        }
        return arr
    }
    console.log(bubbled(arr));  //[1,2,3,4,6]

selection sort

( The complexity is O(n*n), but the time complexity of his data exchange is only O(N). In the process of array sorting, the movement and exchange of data is time-consuming, so compared to bubble sorting, The efficiency of selection sorting is greatly improved. It is suitable for most sorting scenarios, although it has more comparisons, but when the amount of data is large, its efficiency is significantly better than bubbling)

As the name implies, to select and sort, first traverse the array once, select the smallest value and put it in the first position of the array, and then traverse the elements after the second element, and select the smallest value and put it in this sub-none. The first position of the sequence sequence is the second element of the array, so the first two numbers are finished, and so on.

Avati

//选择排序(指挨个挨个遍历,`选择`右侧最小与之交换)
    let arr1 = [2, 4, 1, 6, 3]
    function select(arr1) {
        for (let i = 0; i < arr1.length - 1; i++) {
            let min = i    //保存右侧最小值的下标
            for (let j = i + 1; j < arr1.length; j++) {
                if (arr1[j] < arr1[min]) {
                    //【!!注意】:这里每次循环保存相对较小值的下标
                    min = j
                }
            }
            if (arr1[min] < arr1[i]) {
                let temp;
                temp = arr1[min]
                arr1[min] = arr1[i]
                arr1[i] = temp
            }
        }
        return arr1
    }
    console.log(select(arr1));  //[1,2,3,4,6]

Insertion sort

(Insertion sort is suitable for cases where some existing data is ordered, and the larger the ordered part, the better.)

The complexity of insertion sort is also O(n*n), which involves the movement of elements. First, treat the first element in the array as an ordered sequence, find the elements adjacent to this ordered sequence, compare it with each element in the ordered sequence, and insert it into the appropriate position until the element in the ordered sequence is reached. The ordering is completed by being equal to the elements of the original array.

Avati

 //插入排序
    let arr2 = [2, 4, 1, 6, 3]
    function Ins(arr2) {
        let temp  //专门用于保存作为比较的i项
        for (let i = 1; i < arr2.length; i++) {
            while (i > 0 && arr2[i] < arr2[i - 1]) {
                temp = arr2[i]     //先对后面的值保存一下,因为这个值还要跟前面做对比啊! 你看下一步就要把后面的值覆盖了
                arr2[i] = arr2[i - 1]

                arr2[i - 1] = temp
                i--;
            }
        }
        return arr2
    }
    console.log(Ins(arr2))  //[1,2,3,4,6]

 quick sort

(Quick sort is not suitable for arrays with a high repetition rate of elements.)

Quick sort requires that the length of the subsequences on both sides of the selected pivot value should be the same. The time consumption of quick sort is mainly in the division of elements. For an array with k elements, a total of k-1 comparisons are required. Quick sort mainly depends on the selection of benchmarks. If the selected benchmark is just the smallest or largest element, then the maximum time complexity is O(n*n) at this time. If the selected benchmark is the median of this unordered sequence, the time The minimum complexity is O(nlgn), the total number of keyword comparisons: O(nlgn)

How fast is quick sort? Here is a divide-and-conquer idea. Although recursion is used, although there are worst-case and bubbling, the time complexity of selection sort is equal. However, the idea of ​​divide and conquer is the key. , divide a big problem into two small problems, and deal with them at the same time. These two small problems are further divided down, and finally the problem will be solved. The idea of ​​divide and conquer avoids doing useless work. On the right side, the number smaller than him is on the left side. When comparing, the number on the left side can only be compared on the left side. There is no need to go to the right side for comparison, which saves time.

let arr3 = [2, 4, 1, 6, 3]
    function fast(arr3) {
        if (arr3.length <= 1) return arr3; //【!!!注意】:这一句必须加上,因为有时候递归回来可能左边数组只有一个元素(或空数组),这时直接返回arr ,结束left递归,让它去递归right

        let left = [];
        let right = [];
        let pivot = arr3[0]
        for (let i = 1; i < arr3.length; i++) {
            if (arr3[i] < pivot) {
                left.push(arr3[i])
            } else {
                right.push(arr3[i])
            }
        }
        return fast(left).concat([pivot], fast(right))
    }
    console.log(fast(arr3));   //[1,2,3,4,6]

When testing, I can use my previous blog post to debug the front -end console.time and console.timeEnd

References above


[Summary]: Dachang interviews often test hand-tear code - JavaScript sorting algorithm (bubble sort, selection sort, insertion sort, quick sort) - Programmer Sought
 

Guess you like

Origin blog.csdn.net/u012174809/article/details/123640096