[JS Data Structure and Algorithm] Implementation of bubbling, selection, and insertion sorting algorithms

Preface

A list class has been created for the sorting algorithm: [JS data structure] Encapsulation of the sorting algorithm list

Let's learn how to implement several common sorting algorithms together!

text

1. Bubble sort

The most basic and simplest sorting algorithm.

The main idea

  • The first step is to compare adjacent elements. If the number on the left is larger than the number on the right, then swap the two.
  • The second step is to move to the right and perform the first operation on each pair of adjacent elements. Until the last pair of operations in the list is completed, it is finally determined that the last element is the maximum value.
  • In the third part, repeat the operations of the first and second steps, successively reducing the number of right shifts until there is no pair of elements to compare.

For the following one without a list, we sort it.
Insert picture description here
Animation effect
Insert picture description here
code implementation
If you need to use two numbers to exchange, call the method:

// 交换两个数
ArrayList.prototype.swap = function (a, b) {
    
    
    var temp = this.array[a];
    this.array[a] = this.array[b];
    this.array[b] = temp;
}

Bubble sort algorithm

// 冒泡排序
ArrayList.prototype.bubbleSort = function () {
    
    
    // 1.获取数组的长度
    var length = this.array.length;
    // 第一次: i = 0; 比较0 和1 的位置的两个数据,如果0位置的数据比1位置的数据大,则交换
    // 最后一次: i = length - 2 , 比较的是length - 2 和length - 1的两个数
    for (var i = length - 1; i > 0; i--) {
    
    
        for (var j = 0; j < i; j++) {
    
    
            if (this.array[j] > this.array[j + 1]) {
    
    
                // 2.交换两个数
                this.swap(j, j + 1);
            }
        }
    }
}

The efficiency of bubble sorting
For the above example, we can know that in the 6 data, the total number of times we compare is:
5+4+3+2+1 (times)
Then for the number of N, we can deduce :
(N-1) + (N-2) + (N-3) +… + 1 = N * (N + 1) / 2 (times)
Then in the previous big O notation, we can get The big O notation for bubble sorting is O(N 2 )

Time complexity is O(N 2 )

Optimizing the
bubble sorting requires a total of N * (N + 1) / 2 (times) comparisons. In the worst case, N * (N + 1) / 2 (times) needs to be exchanged. Consider here, in the final position before determining the position of the exchange period it is actually unnecessary, and therefore need to reduce the switching times.

2. Choose sort

Selection sort is an improvement of bubble sort, mainly to reduce the number of exchanges, because not every exchange is necessary, it reduces the number of exchanges from N 2 to N, but the number of comparisons is still N 2 Times.

The main idea

  • The first step is to traverse the entire list and extract the largest (or smallest) element from it and place it at the head of the unsorted list;
  • The second step is to extract the largest (or smallest) element from the remaining unsorted list and place it at the end of the sorted list.
  • In the third part, repeat the operation of the second step, successively reducing the range of extracting the most value until the last digit in the unsorted list.

Bubble Sort
Insert picture description here
Select sorting algorithm

// 选择排序
ArrayList.prototype.selectSort = function () {
    
    
    // 1. 获取数组的长度
    var length = this.array.length,
    min;
    // 2.每一次减少提取最小值的范围,直到未排序序列的最后一个元素。
    for (var i = 0; i < length - 1; i++) {
    
    
        min = i;
        // 第一次:遍历整个数组,选出最小的元素。
        // 第n次:剩下最后一个元素。
        for (var j = min; j < length; j++) {
    
    
            if (this.array[min] > this.array[j]) {
    
    
                min = j;
            }
        }
        // 将最小的数放到已排序序列的末尾
        this.swap(min, i);
    }
}

The efficiency of selective sorting is the
same as that of bubble sorting. In its worst case, the number of comparisons required is also N * (N + 1)/2 (times), but the number of exchanges is reduced, so it is usually considered that selective sorting is executing The efficiency is higher than bubble sort.

Time complexity is O(N 2 )

Optimization The
selection and sorting requires a total of N * (N + 1) / 2 comparisons , and the number of comparisons needs to be reduced .

3. Insertion sort

Insertion sorting is the most efficient of simple sorting (bubbling, selection, insertion).
Before entering advanced sorting, insertion sorting is the foundation, and understanding that insertion sorting is of great help to the understanding of advanced sorting.
The core idea of ​​insertion sort is partial order

What is partial order?
For example, we select a person in the team as the marked player;
then all the players to the left of the marked player are already in order, that is to say, in the process of queuing, some people are sorted, and some are Not sorted.

The main idea

  • The first step is to treat the first element as an ordered list, and the remaining list as an unordered list;
  • The second step is to start with the first element in the unordered list, and insert it into the corresponding position of the ordered list in turn. The comparison during the period is the last of the ordered list and the first of the unordered list, to the order of the ordered list. On the left, perform a sequential comparison for insertion.

It is still the above example for insertion sort,
Bubble Sort
insertion sort animation
Insert picture description here

Insertion sort algorithm

// 插入排序
ArrayList.prototype.insertionSort = function(){
    
    
    // 1. 获取数组的长度
    var length = this.array.length,
    temp,j;

    // 2. 外层循环,从第2个元素(索引为1)开始获取数据,将它作为标记,向前面局部有序的列表中插入
    for(var i = 1; i < length; i++){
    
    
        // 3. 内层循环,将标记元素和前面的数据依次进行比较
        temp = this.array[i];
        j = i;
        // 4. 只要大于标记元素的值,就继续往前面找,在列表范围内直到找到不比标记元素的值大的位置。
        while(this.array[j - 1] > temp && j > 0){
    
    
            this.array[j] = this.array[j - 1];
            j--;
        }

        // 5. 将标记元素插入
        this.array[j] = temp;
    }
}

The efficiency of insertion sort
Although the number of comparisons and exchanges in the worst case is N * (N-1) / 2 (times);
however, the average number of times is only half of the total data items (N * (N-1) / 4) Comparisons and exchanges are required, that is, the sum of the comparison and exchange times of insertion sort is equal to the number of comparisons of selection sort;
therefore, the number of comparisons and exchanges of insertion sort is generally considered to be better than bubble sort and selection Sorts are small, so it is considered that insertion sort is higher in execution efficiency than bubble sort and selection sort.

Time complexity is O(N 2 )

Optimization
Towards advanced algorithms!

to sum up

Sorting algorithms may be used in many situations. For example, the price of the list is sorted in ascending or descending order, or it may be sorted by sales...
Understanding simple sorting algorithms is the prerequisite for understanding advanced sorting algorithms, and learning advanced sorting algorithms must be Incompleteness is too much to bear, so lay the foundation to enter the advanced sorting algorithm! ----"[JS data structure and algorithm] Implementation of Hill sorting and quick sorting algorithms (to be updated)

Guess you like

Origin blog.csdn.net/weixin_42339197/article/details/102907562