Top ten classic sorts

  1. Bubble sorting
    Personal understanding: compare adjacent elements and exchange larger values ​​through a complete cycle to get the maximum value (small value) of the round and put it in the last place. The final sorting result is obtained through multiple rounds of comparison
 	for (var i = 0; i < len - 1; i++) {
        for (var j = 0; j < len - 1 - i; j++) {
            if (arr[j] > arr[j+1]) {        // 相邻元素两两对比
                var temp = arr[j+1];        // 元素交换
                arr[j+1] = arr[j];
                arr[j] = temp;
            }
        }
  1. Selection sort
    Personal understanding: the first time you select the first element and compare it with the subsequent elements in turn to get the large or small value to exchange. Put it in the first place. Through a round, you can determine whether the first element is the maximum or minimum value.
for (var i = 0; i < len - 1; i++) {
        minIndex = i;
        for (var j = i + 1; j < len; j++) {
            if (arr[j] < arr[minIndex]) {     // 寻找最小的数
                minIndex = j;                 // 将最小数的索引保存
            }
        }
        temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }
  1. Insert sorting
    Starting from the first element, the element can be considered to have been sorted; starting from the second element, it is compared with the element at the previous position and then inserted
for (var i = 1; i < len; i++) {
        preIndex = i - 1;
        current = arr[i];
        while (preIndex >= 0 && arr[preIndex] > current) {
            arr[preIndex + 1] = arr[preIndex];
            preIndex--;
        }
        arr[preIndex + 1] = current;
    }

4. Hill sorting
head large do not read

5. Merging and sorting
The input sequence of length n is divided into two subsequences of length n / 2; each subsequence is first ordered, and then the two ordered lists are merged into an ordered list,

Published 16 original articles · praised 0 · visits 834

Guess you like

Origin blog.csdn.net/weixin_45830683/article/details/105248216