US JavaScript data structures and algorithms - The bubble sort, insertion sort, select Sort

US JavaScript data structures and algorithms of

Full Stack practice

1 Introduction

Algorithm is king.

Want to learn the front, first Lianhaoneigong, who only deep internal strength, the front end of the road will go further .

The author wrote the US data structures and algorithms of the JavaScript series with the language is JavaScript , aimed at entry-after data structures and algorithms and easy review.

The reason why 冒泡排序、选择排序、插入排序put them together, because they are the average time complexity of O (n- 2 ).

Please take questions: 为什么插入排序比冒泡排序更受欢迎 ?read below.

2. How to analyze a sorting algorithm

The complexity of the analysis is the essence of the entire algorithm learning.

  • Time complexity: an algorithm execution time taken.
  • Space complexity: End of a desired size to run memory-intensive programs.

Detailed time and complexity of space, see the JavaScript data structures and algorithms of the United States - in time and space complexity .

Learning sorting algorithms, we not only learn how it works algorithm, code implementation, it is more important to learn how to evaluate, analyze a sorting algorithm.

Analysis of a sorting algorithm, from 执行效率, 内存消耗, 稳定性three aspects.

2.1 efficiency

1. best case, worst case, where the average time complexity

When we analyze the time complexity of sorting algorithms, respectively, to give the best case, worst case time complexity of the average case.
In addition, you have to say the best, original data to be sorted worst time complexity corresponds to what.

2. The complexity factor time constant, low-level

We know that the reaction time complexity is a growing trend of large-scale data n the time, so when it represents ignores coefficient, a constant, low-level.

But the actual software development, we sort of could be 10, 100, 1000 such a small scale data, so, at the same time performance of the algorithm sort order time complexity contrast, we want coefficient, constant, low-level is also taken into account.

3. Comparison of the exchange and the number (or mobile) number

This section and the next are telling the sorting algorithm based on the comparison. Sorting algorithm based on the implementation of the comparison involves two operations, one is to compare the size of the element, the other element is moved or exchanged.

So, if when we analyze the efficiency of sorting algorithms, it should be the number of comparisons and exchange (or mobile) number is also taken into account.

2.2 memory consumption

That is, to see the complexity of the space.

Also you need to know the following terms:

  • The sort : Sort all operations are done in memory;
  • External sorting : Since the data is too large, and therefore the data on the disk, and disk and memory sorting through the data transfer can be;
  • Situ Sort : place sorting algorithm, which refer to space complexity is O (1) sorting algorithms.
    Among them, the bubble sort is the place sorting algorithm.

2.3 Stability

  • Stability: If the present value of the sequence to be sorted in 相等the elements, after sorting, the order between the elements of the original are equal 不变.
    For example: a b in front of the original, and a = b, after sorting, a still front of b;
  • Unstable: If the present value of the sequence to be sorted in 相等the elements, after sorting, the order between the elements of the original are equal 改变.
    For example: a b in front of the original, and a = b, after sorting, A b, behind;

3. Bubble Sort

bubble

thought

  • Two adjacent data bubble sort will operate.
  • Every bubble will operate on two adjacent elements are compared to see if it meets the size requirements of the relationship. If not, let Talia interchangeable.
  • A bubbling make at least one element is moved to its position should be repeated n times, to complete the work of the n sorted data.

Feature

  • Advantages: basic sorting algorithm is simple and practical easy to understand.
  • Disadvantages: relatively more often, less efficient.

achieve

// 冒泡排序(未优化)
const bubbleSort = arr => {
    console.time('改进前冒泡排序耗时');
    const length = arr.length;
    if (length <= 1) return;
    // i < length - 1 是因为外层只需要 length-1 次就排好了,第 length 次比较是多余的。
    for (let i = 0; i < length - 1; i++) {
        // j < length - i - 1 是因为内层的 length-i-1 到 length-1 的位置已经排好了,不需要再比较一次。
        for (let j = 0; j < length - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                const temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    console.log('改进前 arr :', arr);
    console.timeEnd('改进前冒泡排序耗时');
};

Optimization: When a particular operation has been no data exchange bubble, the description has been reached fully ordered, no longer continue to perform the subsequent bubbling operation.

// 冒泡排序(已优化)
const bubbleSort2 = arr => {
    console.time('改进后冒泡排序耗时');
    const length = arr.length;
    if (length <= 1) return;
    // i < length - 1 是因为外层只需要 length-1 次就排好了,第 length 次比较是多余的。
    for (let i = 0; i < length - 1; i++) {
        let hasChange = false; // 提前退出冒泡循环的标志位
        // j < length - i - 1 是因为内层的 length-i-1 到 length-1 的位置已经排好了,不需要再比较一次。
        for (let j = 0; j < length - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                const temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                hasChange = true; // 表示有数据交换
            }
        }

        if (!hasChange) break; // 如果 false 说明所有元素已经到位,没有数据交换,提前退出
    }
    console.log('改进后 arr :', arr);
    console.timeEnd('改进后冒泡排序耗时');
};

test

// 测试
const arr = [7, 8, 4, 5, 6, 3, 2, 1];
bubbleSort(arr);
// 改进前 arr : [1, 2, 3, 4, 5, 6, 7, 8]
// 改进前冒泡排序耗时: 0.43798828125ms

const arr2 = [7, 8, 4, 5, 6, 3, 2, 1];
bubbleSort2(arr2);
// 改进后 arr : [1, 2, 3, 4, 5, 6, 7, 8]
// 改进后冒泡排序耗时: 0.318115234375ms

analysis

  • First, the bubble sort is the place sorting algorithm do?
    Bubbling process involves only adjacent data exchange operation, only requires temporary space constant level, so that the space complexity is O (1), a 原地sorting algorithm.
  • Second, the bubble sort is a stable sort algorithm do?
    In the bubble sort, the exchange can only change the order of the two longitudinal elements.
    In order to ensure the stability of the bubble sort algorithm, when there are two adjacent elements of equal size, we do the exchange, the size of the same order of the data does not change before and after sorting.
    So bubble sort is a 稳定sorting algorithm.
  • Third, the time complexity of bubble sort is how much?
    Best case: T (n) = O ( n), when the data is already positive sequence.
    Worst case: T (n-) = O (n- 2 ), when the data is in reverse order.
    Average case: T (n-) = O (n- 2 ).

Animation

Animated bubble sort

Animated bubble sort

4. insertion sort

And insertion sort is divided into direct insertion sort after and optimize the demolition of a half insertion sort and shell sort , insertion sort we usually say refers to direct insertion sort.

First, directly into

thought

Most people play poker, sorting cards when the cards are by size (from small to large or from large to small) finishing cards, that every touch a new card, they scan their cards, the new card into the appropriate s position.

Insertion sort works: by constructing an ordered sequence, for unsorted data, scanning in the sorted sequence from back to front, and find the corresponding insertion positions.

step

  • Starting with the first element, which can be considered to have been sorted;
  • Remove the next element from the forward scan has been sorted in the sequence of elements;
  • If the element (sorted) is greater than the new element, the element to the next position;
  • Repeat step 3 until it finds the sorted elements less than or equal to the new position of the element;
  • After the new element is inserted into this position;
  • Repeat steps 2-5.

achieve

// 插入排序
const insertionSort = array => {
    const len = array.length;
    if (len <= 1) return

    let preIndex, current;
    for (let i = 1; i < len; i++) {
        preIndex = i - 1; //待比较元素的下标
        current = array[i]; //当前元素
        while (preIndex >= 0 && array[preIndex] > current) {
            //前置条件之一: 待比较元素比当前元素大
            array[preIndex + 1] = array[preIndex]; //将待比较元素后移一位
            preIndex--; //游标前移一位
        }
        if (preIndex + 1 != i) {
            //避免同一个元素赋值给自身
            array[preIndex + 1] = current; //将当前元素插入预留空位
            console.log('array :', array);
        }
    }
    return array;
};

test

// 测试
const array = [5, 4, 3, 2, 1];
console.log("原始 array :", array);
insertionSort(array);
// 原始 array:    [5, 4, 3, 2, 1]
// array:        [4, 5, 3, 2, 1]
// array:        [3, 4, 5, 2, 1]
// array:        [2, 3, 4, 5, 1]
// array:        [1, 2, 3, 4, 5]

analysis

  • First, insertion sort sorting algorithm is in place it?
    Insertion sort operation does not require extra storage space, the space complexity is O (1), so this is a 原地sorting algorithm.
  • Second, the insertion sort is a stable sort algorithm do?
    Insertion sorting, the same element value, we can select an element that will appear later, is inserted into the back of the front element occurs, so that you can maintain the original order before and after the change, it is the insertion sort 稳定of sorting algorithm.
  • Third, the time complexity of insertion sort is how much?
    Best case: T (n) = O ( n), when the data is already positive sequence.
    Worst case: T (n-) = O (n- 2 ), when the data is in reverse order.
    Average case: T (n-) = O (n- 2 ).

Animation

insertion-sort.gif

Second, split half inserted

Insertion sort is also an optimization algorithm, called 拆半插入.

thought

Binary sort is inserted directly into an upgraded version of the sort, insertion sort view of a first portion of the exhaust well as sequence arrays, we do not find the insertion point according to the order, simply compare the intermediate value thereof to be inserted to the size of the element.

step

  • Taking the middle point (m = (i-1) >> 1) 0 ~ i-1 is, array [i] and array [m] are compared, if the array [i] [m] <array, it means to be inserted element array [i] should be between 0 ~ m array index; otherwise, it indicates that it should be between m ~ i-1 of the array index.
  • Repeat steps 1, each half of the narrow range lookup, to find the position until insertion.
  • The elements of the array after the insertion position of all the backward one.
  • I-th element is inserted at the specified location.

Note: x >> 1 is a right shift operation in the operation, indicates a right shift, is equivalent to dividing x by 2 and then rounded, i.e. x >> 1 == Math.floor (x / 2).

// 折半插入排序
const binaryInsertionSort = array => {
    const len = array.length;
    if (len <= 1) return;

    let current, i, j, low, high, m;
    for (i = 1; i < len; i++) {
        low = 0;
        high = i - 1;
        current = array[i];

        while (low <= high) {
            //步骤 1 & 2 : 折半查找
            m = (low + high) >> 1; // 注: x>>1 是位运算中的右移运算, 表示右移一位, 等同于 x 除以 2 再取整, 即 x>>1 == Math.floor(x/2) .
            if (array[i] >= array[m]) {
                //值相同时, 切换到高半区,保证稳定性
                low = m + 1; //插入点在高半区
            } else {
                high = m - 1; //插入点在低半区
            }
        }
        for (j = i; j > low; j--) {
            //步骤 3: 插入位置之后的元素全部后移一位
            array[j] = array[j - 1];
            console.log('array2 :', JSON.parse(JSON.stringify(array)));
        }
        array[low] = current; //步骤 4: 插入该元素
    }
    console.log('array2 :', JSON.parse(JSON.stringify(array)));
    return array;
};

test

const array2 = [5, 4, 3, 2, 1];
console.log('原始 array2:', array2);
binaryInsertionSort(array2);
// 原始 array2:  [5, 4, 3, 2, 1]
// array2 :     [5, 5, 3, 2, 1]
// array2 :     [4, 5, 5, 2, 1]
// array2 :     [4, 4, 5, 2, 1]
// array2 :     [3, 4, 5, 5, 1]
// array2 :     [3, 4, 4, 5, 1]
// array2 :     [3, 3, 4, 5, 1]
// array2 :     [2, 3, 4, 5, 5]
// array2 :     [2, 3, 4, 4, 5]
// array2 :     [2, 3, 3, 4, 5]
// array2 :     [2, 2, 3, 4, 5]
// array2 :     [1, 2, 3, 4, 5]

注意: Direct insertion sort and the like, binary insertion sort are adjacent each exchange and the value of different elements, it does not change the order of the same value between the elements, therefore it is stable.

Third, Hill sorting

Shell sort is an average time complexity of O (nlogn) algorithm, will be the next chapter and merge sort, quick sort, heap sort to speak together, it will not start.

5. Selection Sort

Thinking

Realization of ideas selection sorting algorithm is somewhat similar to insertion sort, it can be divided into intervals sorted and unsorted range. But each time the selection sort sort will never find the smallest element in the interval, place it sorted at the end of the interval.

step

  1. First, find the smallest sequence of unsorted (large) element, the starting position is stored in the sorted sequence.
  2. From the remaining unsorted then continue to look for the minimum element (large) element, and then into the end of the sorted sequence.
  3. The second step is repeated until all the elements are sorted completed.

achieve

const selectionSort = array => {
    const len = array.length;
    let minIndex, temp;
    for (let i = 0; i < len - 1; i++) {
        minIndex = i;
        for (let j = i + 1; j < len; j++) {
            if (array[j] < array[minIndex]) {
                // 寻找最小的数
                minIndex = j; // 将最小数的索引保存
            }
        }
        temp = array[i];
        array[i] = array[minIndex];
        array[minIndex] = temp;
        console.log('array: ', array);
    }
    return array;
};

test

// 测试
const array = [5, 4, 3, 2, 1];
console.log('原始array:', array);
selectionSort(array);
// 原始 array:  [5, 4, 3, 2, 1]
// array:        [1, 4, 3, 2, 5]
// array:        [1, 2, 3, 4, 5]
// array:        [1, 2, 3, 4, 5]
// array:        [1, 2, 3, 4, 5]

analysis

  • First, choose a place sorting algorithm to sort it?
    Selection sort space complexity is O (1), a 原地sorting algorithm.
  • Second, selection sort is a stable sort algorithm do?
    Selection Sort minimum value each time looking for the remaining elements are not sorted and the front element and the exchange position, so that damage stability. So selection sort is a 不稳定sorting algorithm.
  • Third, select a sort time complexity is how much?
    Whether it is positive or reverse sequence, selection sort will traverse the n- 2 /2 times to sort, therefore, the best, worst and average complexity is the same.
    Best case: T (n-) = O (n- 2 ).
    Worst case: T (n-) = O (n- 2 ).
    Average case: T (n-) = O (n- 2 ).

Animation

selection-sort.gif

6. Answers opening

Why insertion sort is more popular than the bubble sort?

Bubble sort and insertion sort time complexity is O (the n- 2 ), are in situ sorting algorithms, insertion sort Why are more popular than the bubble sort it?

Here relates to the reverse, full-order degree, degree of order.

  • Degree of ordering : the number of elements in the array is an ordered pair relationship.
    Ordered elements representing the mathematical expression is this:
有序元素对:a[i] <= a[j], 如果 i < j。
  • Full degree of order : the ordering of fully ordered array called the full degree of order .

  • Reverse degree : just the opposite with the degree of order (the default order from small to much).
逆序元素对:a[i] > a[j], 如果 i < j。

Similarly, for an array in reverse order, such as 6,5,4,3,2,1, the degree of ordering is 0;
for a fully ordered array, such as 1,2,3,4,5,6, is the degree of ordering ** n * (n-1) / 2 **, which is a full 15 degree of ordering.

the reason

  • No matter how optimized bubble sort, the number of switching elements is a fixed value, is the reverse of the original data.
  • Insertion sort is the same, no matter how optimization, the number of moving elements is also equal to the reverse order of the original data.
  • However, the bubble sort of data exchange than insertion sort of complex data movement, bubble sort requires three assignment, and requires only one insertion sort, once a large amount of data, and this difference is very obvious.

7. Complexity Comparison

Comparison complexity

name average the best The worst space stability Sort by
Bubble Sort O (N 2 ) O (n) O (N 2 ) O (1) Yes In-place
Insertion Sort O (N 2 ) O (n) O (N 2 ) O (1) Yes In-place
Selection Sort O (N 2 ) O (N 2 ) O (N 2 ) O (1) No In-place

Algorithm visualization tools

It is recommended that a visual tool algorithm.

Algorithm visualization tool algorithm-visualizer is an interactive online platform, the algorithm can be visualized from the code, you can also see the process of code execution.

Results as shown.

Algorithm visualization tools

8. Finally

Like a little star on the point of it.

All of the text in the code and test cases have already put my GitHub on.

Reference article:

Guess you like

Origin www.cnblogs.com/biaochenxuying/p/11444593.html