Common sorting algorithms in JS

Source: Internet
Author: User
This article will introduce in detail the usage of algorithms in JavaScript, and use them in combination with animations to help you learn the principles of algorithms in the fastest way and their usage in scenarios. There is a saying:

Lei Feng pushed down Leifeng Tower, Java implements JavaScript.

In those years, JavaScript (originally called LiveScript), which was not used to give its name to the developer with the help of Java, has become quite simple. The emergence of node JS makes JavaScript available for both front and back ends. Although Java is still dominant in enterprise software development ...), However, in the Web arena, JavaScript was no secret, and he took the lead.

However, in traditional computer algorithms and data structures, the default languages of most professional textbooks and books are Java or C/C ++. This has caused me some trouble recently when I want to search for an algorithm book that uses JavaScript as the default language. When I learned that there is a data structure and algorithm JavaScript description in the o'reilly family's Animal series, it took two days to read the book from start to end. It is a good entry-level algorithm book for front-end developers. However, it has a major drawback: There are many obvious small errors in it, obviously, even programmers like me can see it at a glance. Another problem is that many important algorithms and data structures are not mentioned in this book. These problems cannot be tolerated by me as a patient with advanced obsessive-compulsive disorder. As a result, I decided to find my own summary algorithm. Then, I will summarize the sorting algorithm, the most basic knowledge point in the algorithm field.

I believe that some bugs, errors, non-standard syntax, and other issues may occur in the following code, which cannot be found by myself. Therefore, please point out the errors, it is because I can make long-term progress only on the road of continuous error correction.

Top 10 classic algorithms

JavaScript code implementation

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]) {// Comparison Between Adjacent Elements var temp = arr [j + 1]; // element exchange arr [j + 1] = arr [j]; arr [j] = temp ;}} return arr ;}

Select sort

It represents one of the most stable sorting algorithms, because O (n²) time complexity is applied no matter what data is imported... The smaller the data size, the better. The only benefit is that it does not occupy extra memory.

Select a sequence animation demo

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]) {// find the smallest number minIndex = j; // Save the minimum number of indexes} temp = arr [I]; arr [I] = arr [minIndex]; arr [minIndex] = temp;} return arr ;}

Insert sort

Although the Code Implementation of inserting sorting is not as simple and crude as Bubble sorting and selecting sorting, its principle should be the easiest to understand, because anyone playing poker should be able to understand it in seconds. Of course, if you say that you never sort cards by card size when playing cards, you will not be interested in the insertion Sorting Algorithm in your life...

Like Bubble sorting, insert sorting also has an optimization algorithm called Split semi-insert. For this kind of algorithm, I will apply the classic phrase in the textbook: interested students can study it on their own after class...

Insert a sequence Animation

JavaScript code implementation

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;}

Hill sorting

Hill sorting is a more efficient implementation of insert sorting. It differs from insertion sorting in that it gives priority to elements that are far away from each other. The core of the hill sorting is the setting of the interval sequence. You can set the interval sequence in advance or dynamically define the interval sequence. The algorithm for dynamically defining the interval sequence is proposed by Robert Sedgewick, co-author of the algorithm (version 4th. Here, I use this method.

JavaScript code implementation

Function shellSort (arr) {var len = arr. length, temp, gap = 1; while (gap <len/3) {// dynamically defines the interval sequence 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 ;}

Merge Sorting

As a typical divide-and-conquer algorithm application, merge-sort is implemented in two ways:

● Top-down recursion (all recursive methods can be rewritten by iteration, so there are 2nd methods)

● Bottom-up Iteration

In the data structure and algorithm JavaScript description, the author provides a bottom-up iteration method. However, for Recursive methods, the author believes that:

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

However, this method is not feasible in JavaScript, because the recursive depth of this algorithm is too deep for it.

To be honest, I don't quite understand this sentence. Does it mean that the memory size of the JavaScript compiler is too small and the recursion is too deep, which may cause memory overflow? I hope you can advise me.

Like sorting, the performance of merging sorting is not affected by the input data, but the performance is much better than that of selecting sorting, because it is always the time complexity of O (n log n. The cost is extra memory space.

Merge and sort animations

Merge and sort JavaScript code implementation:

Function mergeSort (arr) {// use the top-down Recursive Method 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 ;}

Quick sorting

Fast sorting is also a typical application of the divide-and-conquer method in sorting algorithms. In essence, quick sorting is a recursive divide-and-conquer method based on Bubble sorting.

Quick name sorting starts with simple and rough, because you will know the meaning of the name as soon as you hear it. It is fast and efficient! It is one of the fastest sorting algorithms for processing big data. Although the time complexity of Worst Case reaches O (n²), it is superior to others. In most cases, the average time complexity is O (n log n) but I don't know why... Fortunately, I made another mistake in obsessive-compulsive disorder. After checking N pieces of data, I finally found a satisfactory answer in the competition of algorithm art and Informatics:

The worst case of fast sorting is O (n²), for example, the fast sorting of sequential series. However, the expected time for its split is O (n log n), and the hidden constant factor in the O (n log n) mark is very small, which is stable and equal to O (n log n) merge Sorting is much smaller. Therefore, fast sorting is always better than Merge Sorting for the vast majority of random series with weak sequence.

Quick Sort animation demo

Implementation of quick sorting JavaScript code:

Function quickSort (arr, left, right) {var len = arr. length, partitionIndex, left = typeof left! = 'Number '? 0: left, right = typeof right! = 'Number '? 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) {// partition operation var partition = left, // set the benchmark value) index = random + 1; for (var I = index; I <= right; I ++) {if (arr [I] <arr [random]) {swap (arr, i, index); index ++;} swap (arr, latency, index-1); return index-1;} function swap (arr, I, j) {var temp = arr [I]; arr [I] = arr [j]; arr [j] = temp ;}

Heap sorting

Heap sorting is a kind of selection sorting that uses the concept of heap. There are two methods:

1. Big Top heap: the value of each node is greater than or equal to the value of its subnodes. It is used in ascending order in the heap sorting algorithm.

2. Small top heap: the value of each node is smaller than or equal to the value of its subnode. It is used in the heap Sorting Algorithm for descending order.

Heap sorting animation demonstration

Implementation of heap sorting JavaScript code:

Var len; // because multiple declared functions require data length, set len to the global variable function buildMaxHeap (arr) {// create a large top heap len = arr. length; for (var I = Math. floor (len/2); I> = 0; I --) {heapify (arr, I) ;}} function heapify (arr, I) {// heap adjustment 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 ;}

Count sorting

The core of counting sorting is to convert the input data values into keys and store them in an extra open array space. As a sort of linear time complexity, counting sorting requires that the input data must be an integer with a definite range.

Counting and sorting animations


JavaScript code implementation for counting and sorting:

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;}

Sort buckets

Bucket sorting is an upgraded version of counting sorting. It uses the ing relationship of the function. The key to the efficiency lies in the determination of the ing function.

To make bucket sorting more efficient, we need to do the following:

1. Increase the number of buckets as much as possible when extra space is sufficient.

2. The ing function can evenly allocate N data entries to K buckets.

In addition, for sorting of elements in a bucket, it is important to select a comparative sorting algorithm that affects the performance.

When is the fastest

When the input data can be evenly distributed to each bucket

When is the slowest

When the input data is allocated to the same bucket

JavaScript code implementation for Bucket sorting:

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]; // minimum value of input data} else if (arr [I]> maxValue) {maxValue = arr [I]; // maximum value of input data }}// initialization var DEFAULT_BUCKET_SIZE = 5; // set the default number of buckets to 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] = [] ;}// use the ing function to allocate data to each bucket 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]); // sort each bucket. Insert sorting is used here (var j = 0; j <buckets [I]. length; j ++) {arr. push (buckets [I] [j]);} return arr ;}

Base sort

There are two ways to sort the base number.

1. MSD sorting starts from high

2. Sort LSD from the low position

Base sort vs count sort vs bucket sort

These three sorting algorithms all use the bucket concept, but there is a significant difference in the use of the bucket:

● Base sorting: the bucket is allocated based on each number of the key value.

● Counting sorting: only one key value is stored in each bucket.

● Bucket sorting: each bucket stores a certain range of values.

LSD base sorting animation demo:

Base sort JavaScript code implementation:

//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;}

Conclusion

The sorting algorithm is very broad and profound, and there are many hin algorithms that I have not summarized or I have not yet figured out. I simply cried out when I summarized these 10 sorting algorithms...

Therefore, if I have mastered more sorting positions in the future, I will definitely be back!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.