Common typical javascript algorithms and javascript Algorithms

Source: Internet
Author: User

Common typical javascript algorithms and javascript Algorithms

Reading directory

  • Bubble Sorting
  • Insert sort
  • Hill sorting
  • Merge Sorting
  • Quick sorting
  • Select sort
  • Parity sorting

Summary

I would like to encourage you to see this sentence in the front-end book. The Foundation determines the height you may reach, and the business determines your lowest bottleneck.

In fact, javascript algorithms are of little use in normal coding, but they do not prevent us from learning them. Learn the ideas of these algorithms and train our own thinking models.

This article will not introduce every method. It will introduce only seven methods. It is purely for learning. If you think the code is not very easy to understand, you can substitute the content in the array into the function.

But it was really a headache at the beginning. Get it up !!

Bubble Sorting

Principle:

Starting from the first element, after comparison, an element smaller than itself is exchanged

(From Baidu images)

Features:

The highest number of exchanges, so its performance is the worst.

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]; // interaction location, so the big data is put to the end of arr [j + 1] = arr [j]; arr [j] = temp ;}} return arr ;}var arr = [2, 3, 6, 4, 2, 1, 90,100, 20, 5]; console. log (bubbleSort (arr); // [1, 2, 2, 3, 4, 5, 6, 20, 90,100]

Insert sort

Principle:

The basic operation of insert sorting is to insert a data to an ordered data that has already been sorted, so as to get a new ordered data with a number plus one.

In insert sorting, arrays are divided into two types: "ordered array blocks" and "unordered array blocks ",

At the first time, extract a number 20 from the unordered array block as the ordered array block.

At the second time, extract a 60 ordered number from the unordered array block and put it in the "ordered array block", that is, 20, 60.

The third time is the same. The difference is that 10 is smaller than the value of the ordered array. Therefore, the value is shifted at the position of 20 and 60, freeing up a position for 10 insertion.

Then, all the data can be inserted according to this rule.

Below is a gif Image

Features:

The insert algorithm divides the array to be sorted into two parts:

The first part contains all the elements of this array, except the first element (so that the array has more space to insert ).

The second part only contains this element (that is, the element to be inserted ). After sorting the first part, insert the last element to the first part of the sorted part.

Faster than Bubble Sorting

Code implementation:

// Insert sorting // assuming that the elements before the current element have already sorted out their order, first empty their positions, // then move the elements that are later than themselves in turn, until a "pitfall" is empty, // then insert the target element into the "pitfall" function insertSort (arr) {// starts with the second element, because we need to leave a hole for (var I = 1; I <arr. length; I ++) {var x = arr [I]; for (var j = I-1; arr [j]> x; j --) {// The Position of the backend void. arr [j + 1] = arr [j];} if (arr [j + 1]! = X) {arr [j + 1] = x;} return arr;} var arr = [90,100,]; console. log (insertSort (arr, 2); // [1, 2, 2, 3, 4, 5, 6, 20, 90,100]

Hill sorting

Principle:

Hill sorting is also called the descending incremental sorting algorithm. It is an evolutionary version of insert sorting.

What is a descending increment? It defines an interval sequence, for example, 5, 3, and 1. For the first processing, all the five intervals are processed,

The next processing interval is 3 and the last processing interval is 1. That is, standard insertion sorting is executed for adjacent elements.

The procedure is as follows:

1. Take an integer d1 less than n as the first increment, and divide all records of the file into d1 groups.

2. All records whose distance is multiples of d1 are placed in the same group and inserted in each group for sorting.

3. Take the second incremental d2 <d1 repeat the preceding grouping and sorting,

4. Until the incremental dt = 1 (dt <dt-l <... <D2 <d1), that is, all records are placed in the same group for direct insertion sorting.

Here, the incremental method is as follows:

The first incremental method is d = count/2;

The method for obtaining the second increment is: d = (count/2)/2;

Last until: d = 1;

The observed phenomena are:

D = 3: Compare the value of 40 to 50, because the value of 50 is large, it is not exchanged.

Compare 20 to 30, because 30 is large, do not exchange.

Compare 80 to 60 because 60 is small.

D = 2: Compare 40 to 60, do not exchange, take 60 to 30 ratio exchange, then the 30 after the exchange is more than 40 smaller than the previous 40, but also 40 and 30 exchange, for example.

Compare 20 to 50, do not exchange, continue to compare 50 to 80, do not exchange.

D = 1: This is the insertion sorting mentioned earlier. However, the sequence is almost ordered, which greatly improves the insertion sorting performance.

Features:

Because of the multiple insertion sorting, we know that one insertion sorting is stable and does not change the relative order of the same elements. However, in different insertion sorting processes,

The same elements may move in their respective insert sorting, and the final stability will be disrupted, so shell sorting is unstable.

For example, my original array is [5, 4, 3, 2, 1], and all of them are rescheduled.

Code implementation:

 function shellSort(arr){ var gap=Math.floor(arr.length/2); while(gap>0){ for(var i=gap;i<arr.length;i++){  temp=arr[i];  for(var j=i;j>=gap&&arr[j-gap]>temp;j-=gap){  arr[j]=arr[j-gap];  }  arr[j]=temp; } gap=Math.floor(gap/2); } return arr;}var arr = [2,3,6,4,2,1,90,100,20,5];console.log(shellSort(arr)); //[1, 2, 2, 3, 4, 5, 6, 20, 90, 100]

Merge Sorting

Principle:

The Merge Sorting method combines two (or more) ordered tables into a new ordered table, that is, the sequence to be sorted is divided into several sub-sequences, each of which is ordered. Then combine the ordered subsequences into the overall ordered sequence.

Perform the following steps:

1. Divide an input sequence whose length is n into two subsequences whose length is n/2;

2. Continue to divide these two subsequences into sub-sequences of m/2 and continue to divide them down.

3. merge two sorted subsequences into a final sorting sequence.

A static graph is better understood.

Here, we need to add that the division of arrays in the merge operation is from top to bottom, and the comparison of arrays in the merge operation is from bottom to top.

Features:

The speed is second only to fast sorting, and is a stable sorting algorithm. It is generally used for a series of unordered items, but each subitem is relatively ordered.

It belongs to the sub-governance idea and is recursive and merged

Code implementation:

/* Sort and merge */function merge (left, right) {var re = []; while (left. length> 0 & right. length> 0) {if (left [0] <right [0]) {// if the left data is smaller than the right data, extract the left data, put it in the new array. re. push (left. shift ();} else {re. push (right. shift ();}/* when the length of the left and right arrays is not equal. link the remaining array necklace after comparison. */return re. concat (left ). concat (right);} function mergeSort (arr) {if (arr. length = 1) {return arr;}/* first divides the unordered array into two arrays */var mid = Math. floor (arr. length/2); var left = arr. slice (0, mid); var right = arr. slice (mid);/* recursively sort and merge the left and right arrays respectively */return merge (mergeSort (left), mergeSort (right);} var arr = [2, 3, 6, 4, 2, 1, 90,100, 20, 5]; console. log (mergeSort (arr); // [1, 2, 2, 3, 4, 5, 6, 20, 90,100]

Quick sorting

Principle:

1. Select an element in the dataset as the "benchmark ). For example, select the number 45 below.

2. All elements smaller than the "benchmark" are moved to the left of the "benchmark"; all elements greater than the "benchmark" are moved to the right of the "benchmark.

3. For the Left and Right subsets of the benchmark, repeat Step 1 and Step 2 until only one element is left in all subsets.

Features: The fastest speed. Different from Merge Sorting, Merge Sorting is divided into two groups before resuming sorting, while quick sorting is edge sharding.

Code implementation:

// Roughly divided into three steps: // 1. Search for the benchmark (usually based on the intermediate item) // 2. traverse the array and place the baseline less than left, placed above the benchmark in right // 3, recursive function quickSort (arr) {// if the array is <= 1, the if (arr. length <= 1) {return arr;} var variable tindex = Math. floor (arr. length/2); // locate the reference and delete the reference from the original array. splice (tindex, 1) [0]; // defines the left and right arrays var left = []; var right = []; // left is smaller than the benchmark, placed right for (var I = 0; I <arr. length; I ++) {if (arr [I] <= cursor) {left. push (arr [I]);} else {right. push (arr [I]) ;}// recursive return quickSort (left ). concat ([activities], quickSort (right);} var arr = [90,100,]; console. log (quickSort (arr); // [1, 2, 2, 3, 4, 5, 6, 20, 90,100]

Select sort

Principle: In the number of a group to be sorted, the minimum number is selected to exchange with the number at the first position, and then the smallest number is found in the remaining number to exchange with the number at the second position, this loop ends until the second to last and the last number.

Static graph:

Features: It can be said that it is a derivative of the bubble sort, and the efficiency is average.

Code implementation:

// Select the smallest element in the unordered area and switch it to the first element in the unordered area. Function selectSort (arr) {length = arr. length; for (var I = 0; I <length; I ++) {// circular array var _ min = arr [I]; // record the numbers in each array as var k = I; // record the index for (var j = I + 1; j <length; j ++) {// compare the current number with the next number if (_ min> arr [j]) {// if the current number is greater than the next one _ min = arr [j]; // Save the subsequent values k = j; // Save the index} arr [k] = arr [I]; // Switch location arr [I] = _ min;} return arr;} var arr = [90,100,]; console. log (selectSort (arr); // [1, 2, 2, 3, 4, 5, 6, 20, 90,100]

Parity sorting

Principle:

Select the elements of all odd series and the elements adjacent to the Right to sort the smaller elements in front;

Compare the elements of all even columns with the adjacent elements on the Right To sort small elements in front;

Repeat the previous two steps until all the sequences are ordered.

As shown in:

Gif:

Features:Alternating comparison of odd and even numbers

Code implementation:

Function oddEvenSort (arr) {// swaped is used to control whether the loop is going to continue. If the left side is smaller than the right side, the loop is exited and the sorted array var swaped = true is returned; var k = 0; while (swaped) {if (k> 0) {swaped = false;} for (var I = k; I <arr. length-1; I + = 2) {if (arr [I]> arr [I + 1]) {// if the number on the left is greater than the number on the right, switch between the two: arr [I] = [arr [I + 1], arr [I + 1] = arr [I] [0]; swaped = true ;}} k = [90,100] [k]; // returns arr;} var arr = [,]; console. log (oddEvenSort (arr); // [1, 2, 2, 3, 4, 5, 6, 20, 90,100]

Summary

This article only summarizes part of the algorithm. The essence of the algorithm lies in their ideas. It should not be very useful in js. If you do not understand the code for the first time, you can try to repeat it by yourself. When I sum up the code that I cannot understand, I will deepen my understanding.

After understanding it, it is true that these algorithms have broad and profound Implementation ideas, and you have to feel the depth of the ideas of our predecessors.

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

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.