Home > Web Front-end > JS Tutorial > Detailed explanation of common sorting algorithms in JS

Detailed explanation of common sorting algorithms in JS

阿神
Release: 2017-01-24 13:47:51
Original
1040 people have browsed it

There is a saying:

Lei Feng knocked down Leifeng Pagoda, Java implements JavaScript.

Back then, I wanted to become popular by embracing Java. JavaScript (formerly known as LiveScript), which did not hesitate to change its name, is now shining brightly. node The emergence of JS allows JavaScript to take over both the front and back ends. Although Java still dominates the field of enterprise software development (C/C + + Great gods, please don’t hit me. . . ), but in the world of the Web, JavaScript is unparalleled and takes the top spot.

However, in the field of traditional computer algorithms and data structures, the default language of most professional textbooks and books is Java or C/C+ +. This has caused some trouble for me, who recently wanted to supplement the knowledge of algorithms and data structures, because I wanted to find an algorithm book with JavaScript as the default language. When I learned that there was a book in O’REILLY’s animal book series called “JavaScript Description of Data Structures and Algorithms”, I excitedly spent two days reading this book from cover to cover. It is a good introductory algorithm book for front-end developers. However, it has a big flaw, that is, there are many obvious small errors in it, which are so obvious that even a half-way programmer like me can spot them at a glance. figure it out. Another problem is that many important algorithms and data structure knowledge are not mentioned in this book. These problems are simply intolerable to me as a late-stage obsessive-compulsive disorder patient. So, whenever I disagreed, I decided to look for information and summarize the algorithm myself. So, I will summarize it from the most basic knowledge point in the algorithm field-sorting algorithm.

I believe that there must be some bugs or errors or irregular grammar in the following code that I cannot find myself, so I hope you can point out the errors, because only by constantly correcting them can I Only by doing this can I make long-term progress.


##Top Ten Classic Algorithms

Detailed explanation of common sorting algorithms in JS

Explanation of terms:

n: Data scale

k: The number of “buckets”

In-place: Occupies constant memory, does not occupy additional memory

Out-place: Occupies additional memory

Stability: The order of two equal key values ​​after sorting is the same as their order before sorting


Bubble sorting

As one of the simplest sorting algorithms, bubble sorting gives me the same feeling as Abandon appears in a word book. It is in the first place on the first page every time, so it is the most familiar. . . There is another optimization algorithm for bubble sorting, which is to set a flag. When the elements are not exchanged during a sequence traversal, it proves that the sequence is in order. But this improvement doesn't do much to improve performance. . .

When is the fastest time?

When the input data is already in positive sequence (it is already in positive sequence), what is the use of bubble sorting? . . )

When is the slowest time?

When the input data is in reverse order (it is not enough to write a for loop to output the data in reverse order, why use it? Are you doing bubble sorting? .)

Bubble sorting animation

##JavaScript code implementationDetailed explanation of common sorting algorithms in JS

function bubbleSort(arr) {
    var len = arr.length;
    for (var i = 0; i < len; 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;
            }
        }
    }
    return arr;
}
Copy after login

##Selection sort


One of the most stable sorting algorithms, because no matter what data is entered, the time complexity is O(n²). . . So when using it, the smaller the data size, the better. The only advantage may be that it does not occupy additional memory space. Select sorting animation demonstration

JavaScript code implementation

function selectionSort(arr) {
    var len = arr.length;
    var minIndex, temp;
    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;
    }
    return arr;}
Copy after login
Detailed explanation of common sorting algorithms in JS

Insertion sort


The code implementation of insertion sort is not as good as bubble sort and selection sort. It is simple and crude, but its principle should be the easiest to understand, because anyone who has played poker should be able to understand it instantly. Of course, if you say that you never sort the cards according to their size when playing poker, then you probably won’t have any interest in the insertion sort algorithm in this life. . . Insertion sort, like bubble sort, also has an optimization algorithm called split-half insertion. For this kind of algorithm, I, being lazy, will use a classic saying from the textbook: interested students can study it on their own after class. . .

Insertion sort animation demonstration

JavaScript代码实现

function insertionSort(arr) {
    var len = arr.length;
    var preIndex, current;
    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;
    }
    return arr;}
Copy after login


希尔排序

希尔排序是插入排序的一种更高效率的实现。它与插入排序的不同之处在于,它会优先比较距离较远的元素。希尔排序的核心在于间隔序列的设定。既可以提前设定好间隔序列,也可以动态的定义间隔序列。动态定义间隔序列的算法是《算法(第4版》的合著者Robert Sedgewick提出的。在这里,我就使用了这种方法。

JavaScript代码实现

function shellSort(arr) {
    var len = arr.length,
        temp,
        gap = 1;
    while(gap < len/3) {          //动态定义间隔序列
        gap =gap*3+1;
    }
    for (gap; gap > 0; gap = Math.floor(gap/3)) {
        for (var i = gap; i < len; i++) {
            temp = arr[i];
            for (var j = i-gap; j >= 0 && arr[j] > temp; j-=gap) {
                arr[j+gap] = arr[j];
            }
            arr[j+gap] = temp;
        }
    }
    return arr;}
Copy after login


归并排序

作为一种典型的分而治之思想的算法应用,归并排序的实现由两种方法:

●自上而下的递归(所有递归的方法都可以用迭代重写,所以就有了第2种方法)

●自下而上的迭代

在《数据结构与算法JavaScript描述》中,作者给出了自下而上的迭代方法。但是对于递归法,作者却认为:

However, it is not possible to do so in JavaScript, as the recursion goes too deep for the language to handle.

然而,在 JavaScript 中这种方式不太可行,因为这个算法的递归深度对它来讲太深了。

说实话,我不太理解这句话。意思是JavaScript编译器内存太小,递归太深容易造成内存溢出吗?还望有大神能够指教。

和选择排序一样,归并排序的性能不受输入数据的影响,但表现比选择排序好的多,因为始终都是O(n log n)的时间复杂度。代价是需要额外的内存空间。

归并排序动图演示

Detailed explanation of common sorting algorithms in JS

归并排序JavaScript代码实现:

function mergeSort(arr) {  //采用自上而下的递归方法
    var len = arr.length;
    if(len < 2) {
        return arr;
    }
    var middle = Math.floor(len / 2),
        left = arr.slice(0, middle),
        right = arr.slice(middle);
    return merge(mergeSort(left), mergeSort(right));}function merge(left, right){
    var result = [];

    while (left.length && right.length) {
        if (left[0] <= right[0]) {
            result.push(left.shift());
        } else {
            result.push(right.shift());
        }
    }

    while (left.length)
        result.push(left.shift());

    while (right.length)
        result.push(right.shift());

    return result;}
Copy after login


快速排序

快速排序又是一种分而治之思想在排序算法上的典型应用。本质上来看,快速排序应该算是在冒泡排序基础上的递归分治法。

快速排序的名字起的是简单粗暴,因为一听到这个名字你就知道它存在的意义,就是快,而且效率高! 它是处理大数据最快的排序算法之一了。虽然Worst Case的时间复杂度达到了O(n²),但是人家就是优秀,在大多数情况下都比平均时间复杂度为O(n log n) 的排序算法表现要更好,可是这是为什么呢,我也不知道。。。好在我的强迫症又犯了,查了N多资料终于在《算法艺术与信息学竞赛》上找到了满意的答案:

快速排序的最坏运行情况是O(n²),比如说顺序数列的快排。但它的平摊期望时间是O(n log n) ,且O(n log n)记号中隐含的常数因子很小,比复杂度稳定等于O(n log n)的归并排序要小很多。所以,对绝大多数顺序性较弱的随机数列而言,快速排序总是优于归并排序。

快速排序动图演示

Detailed explanation of common sorting algorithms in JS

快速排序JavaScript代码实现:

function quickSort(arr, left, right) {
    var len = arr.length,
        partitionIndex,
        left = typeof left != &#39;number&#39; ? 0 : left,
        right = typeof right != &#39;number&#39; ? len - 1 : right;

    if (left < right) {
        partitionIndex = partition(arr, left, right);
        quickSort(arr, left, partitionIndex-1);
        quickSort(arr, partitionIndex+1, right);
    }
    return arr;}function partition(arr, left ,right) {     //分区操作
    var pivot = left,                      //设定基准值(pivot)
        index = pivot + 1;
    for (var i = index; i <= right; i++) {
        if (arr[i] < arr[pivot]) {
            swap(arr, i, index);
            index++;
        }        
    }
    swap(arr, pivot, index - 1);
    return index-1;}function swap(arr, i, j) {
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;}
Copy after login


堆排序

堆排序可以说是一种利用堆的概念来排序的选择排序。分为两种方法:

1.大顶堆:每个节点的值都大于或等于其子节点的值,在堆排序算法中用于升序排列

2.小顶堆:每个节点的值都小于或等于其子节点的值,在堆排序算法中用于降序排列

堆排序动图演示

Detailed explanation of common sorting algorithms in JS

堆排序JavaScript代码实现:

var len;    //因为声明的多个函数都需要数据长度,所以把len设置成为全局变量function buildMaxHeap(arr) {   //建立大顶堆
    len = arr.length;
    for (var i = Math.floor(len/2); i >= 0; i--) {
        heapify(arr, i);
    }}function heapify(arr, i) {     //堆调整
    var left = 2 * i + 1,
        right = 2 * i + 2,
        largest = i;

    if (left < len && arr[left] > arr[largest]) {
        largest = left;
    }

    if (right < len && arr[right] > arr[largest]) {
        largest = right;
    }

    if (largest != i) {
        swap(arr, i, largest);
        heapify(arr, largest);
    }}function swap(arr, i, j) {
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;}function heapSort(arr) {
    buildMaxHeap(arr);

    for (var i = arr.length-1; i > 0; i--) {
        swap(arr, 0, i);
        len--;
        heapify(arr, 0);
    }
    return arr;}
Copy after login


计数排序

计数排序的核心在于将输入的数据值转化为键存储在额外开辟的数组空间中。作为一种线性时间复杂度的排序,计数排序要求输入的数据必须是有确定范围的整数。

计数排序动图演示


Detailed explanation of common sorting algorithms in JS

计数排序JavaScript代码实现:

function countingSort(arr, maxValue) {
    var bucket = new Array(maxValue+1),
        sortedIndex = 0;
        arrLen = arr.length,
        bucketLen = maxValue + 1;

    for (var i = 0; i < arrLen; i++) {
        if (!bucket[arr[i]]) {
            bucket[arr[i]] = 0;
        }
        bucket[arr[i]]++;
    }

    for (var j = 0; j < bucketLen; j++) {
        while(bucket[j] > 0) {
            arr[sortedIndex++] = j;
            bucket[j]--;
        }
    }

    return arr;}
Copy after login


桶排序

桶排序是计数排序的升级版。它利用了函数的映射关系,高效与否的关键就在于这个映射函数的确定。

为了使桶排序更加高效,我们需要做到这两点:

1.在额外空间充足的情况下,尽量增大桶的数量

2.使用的映射函数能够将输入的N个数据均匀的分配到K个桶中

同时,对于桶中元素的排序,选择何种比较排序算法对于性能的影响至关重要。

什么时候最快

当输入的数据可以均匀的分配到每一个桶中

什么时候最慢

当输入的数据被分配到了同一个桶中

桶排序JavaScript代码实现:

function bucketSort(arr, bucketSize) {
    if (arr.length === 0) {
      return arr;
    }

    var i;
    var minValue = arr[0];
    var maxValue = arr[0];
    for (i = 1; i < arr.length; i++) {
      if (arr[i] < minValue) {
          minValue = arr[i];                //输入数据的最小值
      } else if (arr[i] > maxValue) {
          maxValue = arr[i];                //输入数据的最大值
      }
    }

    //桶的初始化
    var DEFAULT_BUCKET_SIZE = 5;            //设置桶的默认数量为5
    bucketSize = bucketSize || DEFAULT_BUCKET_SIZE;
    var bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1;   
    var buckets = new Array(bucketCount);
    for (i = 0; i < buckets.length; i++) {
        buckets[i] = [];
    }

    //利用映射函数将数据分配到各个桶中
    for (i = 0; i < arr.length; i++) {
        buckets[Math.floor((arr[i] - minValue) / bucketSize)].push(arr[i]);
    }

    arr.length = 0;
    for (i = 0; i < buckets.length; i++) {
        insertionSort(buckets[i]);                      //对每个桶进行排序,这里使用了插入排序
        for (var j = 0; j < buckets[i].length; j++) {
            arr.push(buckets[i][j]);                      
        }
    }

    return arr;}
Copy after login


基数排序

基数排序有两种方法

1.MSD 从高位开始进行排序

2.LSD 从低位开始进行排序

基数排序 vs 计数排序 vs 桶排序

这三种排序算法都利用了桶的概念,但对桶的使用方法上有明显差异:

●基数排序:根据键值的每位数字来分配桶

●计数排序:每个桶只存储单一键值

●桶排序:每个桶存储一定范围的数值

LSD基数排序动图演示:

Detailed explanation of common sorting algorithms in JS

基数排序JavaScript代码实现:

//LSD Radix Sortvar counter = [];function radixSort(arr, maxDigit) {
    var mod = 10;
    var dev = 1;
    for (var i = 0; i < maxDigit; i++, dev *= 10, mod *= 10) {
        for(var j = 0; j < arr.length; j++) {
            var bucket = parseInt((arr[j] % mod) / dev);
            if(counter[bucket]==null) {
                counter[bucket] = [];
            }
            counter[bucket].push(arr[j]);
        }
        var pos = 0;
        for(var j = 0; j < counter.length; j++) {
            var value = null;
            if(counter[j]!=null) {
                while ((value = counter[j].shift()) != null) {
                      arr[pos++] = value;
                }
          }
        }
    }
    return arr;}
Copy after login


写在最后

排序算法实在是博大精深,还有hin多hin多我没有总结到或者我自己还没弄明白的算法,仅仅是总结这十种排序算法都把我写哭了。。。

因此,以后如果我掌握了更多的排序姿势,我一定还会回来的!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template