The first glimpse of JS algorithm 02 (Sort algorithm 02-merge, Fast and heap sort)

Source: Internet
Author: User
Tags array length array sort

On an article, we describe some simple sorting algorithm, in fact, in the front-end career, do not involve node, do not involve the background of the situation, I really did not think of what can be used in these data structures and algorithms, but I also said in the previous article. Maybe you can't use it, but, really, if you want to have a good development in the front-end area. Data structures and algorithms must be a required course for you. It not only let you in the process of dealing with a problem can have a mind, more importantly, in the face of some wonderful products, you can and he pk in the end! Well, in the end!

Haha, a little joke. Let's talk about some nutritious. The previous algorithm is relatively simple, the main content is the loop, the second content is the comparison. However, some of the algorithms introduced in this article, in the implementation of some of the complexity, even involved in a part of the data structure related knowledge, if you are not very understanding of data structure, please go here with JS to implement those data structure-directory.

So, let's take a look at this article. Other algorithms that perform more efficiently, such as merge sorting, such as fast sorting, heap sorting, and so on.

1. Merge sort

  Let's take a look at what the merge sort is and how the merge sort is implemented.

Merge sort belongs to a kind of divide and conquer algorithm. The idea of merge sorting is to cut the original array into a smaller array until each group has only one element, and then combine one decimal group, 1.1 points, into a final sorted array. In fact, in simple terms, it is the first minute, then close. There are two ways to implement merge sorting, one is recursion and one is iteration. The following is a recursive way to implement the code:

//Merge Sort//don't say more, you know.  This. MergeSort =function() {array=Mergesortrec (array);};//This private function, in fact, is the whole "points" part of the merge sort. Let's see how it's "divided". varMergesortrec =function(array) {//stores the array length.     varLength =Array.Length; //because it is recursive, when the length is 1, it means that we are divided into the end. Returns the array directly. That is, an array of only one element.     //at the same time this judgment condition is also the terminating condition of recursion, remember that any recursive operation must have a termination condition. Otherwise it will fall into a cycle of death.     if(Length = = 1) {        returnArray; }    //We're going to split the original array from the other. Here is the split operation. Needless to say.     varMid = Math.floor (LENGTH/2), left= Array.slice (0, mid), right=Array.slice (mid,length); //here, let's not take care of what the merge function does. Let's look at the bottom of the recursion first. What the two parameters of the merge will become.     //as we return to ourselves, the recursion is formed. In the parameters of the merge we recursively call ourselves once again.     //so this call we split the left and right two arrays again. Until the last Array.Length is 1 (the smallest unit in the merge).     //so in other words, actually the bottom of the merge function recursion is two arrays with only one element.     returnmerge (Mergesortrec (left), Mergesortrec (right));};varMerge =function(left,right) {//we declare an array result of the final result,    //IL and IR are variables used to control the iterations of the left and right two arrays    varresult = [],il = 0,ir = 0; //here, our bottom level is that there are only two arrays of only one element    /*Array[left] and Array[right] The first while, the condition of the loop is whether the two-length variable is within a valid value. */     while(Il < left.length && IR <right.length) {//If the left side is less than the right, the IL and IR are equal at 0. Pay attention to this point        //we put the left Left[il] into the array and il++. Otherwise, we will put Right[ir] into the array result and ir++. At this point, the IL and IR are not equal.         //So, at this point, the next time we loop to judge the condition is that the IR or IL increment is compared with the IL or IR without increment. This allows one element to be compared to all elements in another array.         //I hope that I understand the meaning of the words I want to express.         if(Left[il] <Right[ir]) {            //here, it's not easy to understand. Why do we add il++ instead of IL to result?            //In fact, this means, first add as Left[il] and then il++.             //No, you can change the code to look like this.            /*Result.push (Left[il]); il++*/            //the effect is the same. Result.push (left[il++]); } Else{Result.push (Right[ir++]);    }    }; //The purpose of these two loops is to deposit the remaining array elements (both the left and right arrays) into the result array.     //so we're going to have a merged result array, and then the initial parameters for the next merge process.      while(Il <left.length) {Result.push (Left[il++]);    };  while(IR <right.length) {Result.push (Right[ir++]);    }; returnresult;};//Let's use the previous chapter to test the merge sortvarArrayList = Creatarraylist (5); Console.log (arraylist.tostring ());//5,4,3,2,1Arraylist.mergesort (); Console.log (arraylist.tostring ());//1,2,3,4,5

In fact, the core idea of merge sorting is to split the fractional group into an array of only one element and then merge the 1.1 points.

2. Quick Sort

Fast sorting is one of the most commonly used sorting algorithms in your organization or in the real world, and you can also use quick sorting in your project.

The idea of quick sorting is somewhat similar to the merge sort, but the quick sort does not need to load the split elements into a new array, but rather to swap them directly on the original array.

So let's take a look at the quick sort operation steps:

First we need to find the "main element" to compare with. In theory, a principal can be an arbitrary element in an array, but in this article we select the middle term of the arrays as the principal element.

We then select the elements in the two parts of the left and right sides of the main element to compare with the main element, until we find the element that is larger on the left than the main element and the right side is smaller than the primary, then we swap the position of the two elements. Until the left hand of the iteration exceeds the right hand pointer. In this way, we make the elements that are smaller than the main element and those that are larger than the main element exist on either side of the main element, respectively.

Finally, we repeat the above steps on the left and right side of the array recursively. Until the array sort ends.

Let's look at the code.

//Quick Sort This. QuickSort =function () {    //the parameters passed in here are the subscripts of the original array itself and the end-to-end elements. Quick (array,0,array.length-1);};varQuick =function(array,left,right) {//This index is to help us isolate the array of smaller and larger values    varindex; //if Length>1 does not perform logic, because only an array of elements means no ordering.     if(Array.Length > 1) {        //Partition returns the subscript of an element. index =partition (Array,left,right); //here are two criteria for determining whether we want to recursively return a smaller or larger array of values.         if(Left < Index-1) {Quick (Array,left,index-1);        }; if(Index <Right )        {Quick (array,index,right);    }; }};//Let's take a look at this approach to the partitioning process.varPartition =function(array,left,right) {//Pivot (the principal element), which is the element we want to compare with. We select the middle item as the main element.     //I and J represent pointers to the current elements of a smaller array and a larger array of values    varPivot = Array[math.floor (right + left)/2)],i = Left,j =Right ; //to know that the very beginning of I is 0,j is lenght-1. So i++ is moving the pointer to the right, and j--is moving the pointer to the left.     //The condition of the loop is that the subscript of the array of smaller values is less than the subscript of the larger value array.      while(I <=j) {//if the array[i] element is smaller than the main element, move the pointer to the right.          while(Array[i] <pivot) {i++;        }; //if the array[j] element is larger than the main element, move the pointer to the left.          while(Array[j] >pivot) {J--;        }; //The above two while iterations will stop when they encounter a non-conforming condition.         //This condition of non-compliance is array[i]>array[j]. This is the situation to be adjusted. But at this point I is still less than or equal to J. Be aware that I cannot be larger here than J.         //so we swapped two subscript corresponding elements and changed the pointers of I and J. Finally, the subscript i is returned.         if(I <=j) {swap (ARRAY,I,J); I++; J--;    };    }; returni;};varArrayList = Creatarraylist (5); Console.log (arraylist.tostring ());//5,4,3,2,1Arraylist.quicksort (); Console.log (arraylist.tostring ());//1,2,3,4,5


3. Heap Sequencing

Before we talk about heap sequencing, we need to understand what a heap is, and the nature of the heap is a completely binary tree (if you don't know what a tree is, see my previous article), then since the heap is a tree, some concepts about trees can be used on the heap, such as depth, such as nodes. You know, a tree usually has a pointer to a left child and a child node and a parent node, but in a fully binary tree, these pointers can be removed, because we can use a certain pattern to directly find the node's associated node. For example, given a certain node, assuming its subscript is I, then its left child node subscript is 2i + 1, the right child node subscript is 2i + 2, its parent node is (i?1)/2. In this way, we can omit these pointers and store the nodes in the heap directly in the array.

After knowing what the heap is, let's look at how the heap sort is done. We'll just see the specifics from the code:

//Heap Sort//Here you need to have a certain understanding and understanding of the tree data structure. If you are not familiar with the tree structure, see the related chapters in the tree structure that I have earlier. //Alternatively, you can use the following code directly to solve the problem, of course, you need to make some minor changes.  This. Heapsort =function () {    //Save the array length to a variable    varHeapSize =Array.Length; //"Heap" the array. buildheap (array); //iteration decrements the length of the heapsize, the swap array is labeled 0 and the current heapsize re-"rationalize" the changed heap. The rationalization here is that the array that swapped the element position is regenerated to a new array that conforms to the heap principle.      while(HeapSize > 1) {heapsize--; Swap (Array,0, heapsize); Heapify (Array,heapsize,0); };};//With a heap of functions, our I is an array of intermediate values and the loop of decrement I is passed in for the Heapify function. varBuildheap =function(array) {varHeapSize =Array.Length;  for(vari = Math.floor (ARRAY.LENGTH/2); I >= 0; i--) {heapify (array,heapsize,i); };};//A "heap" of functions. varHeapify =function(array,heapsize,i) {//we declare the left node, the right node, and the variables of the parent node (that is, largest)    varleft = i * 2 + 1, Right= i * 2 + 2, Largest=i; //these two judgments are to know who the parent node is in the current wheel.     if(Left < heapsize && Array[left] >Array[largest]) {Largest=Left ;    }; if(Right < HeapSize && Array[right] >Array[largest]) {Largest=Right ;    }; //If largest changes, we need to exchange two worth of places. and call Heapify again.     if(Largest!==i) {swap (array,i,largest);    Heapify (array,heapsize,largest); };};varArrayList = Creatarraylist (125); Console.log (arraylist.tostring ());//5,4,3,2,1Arraylist.heapsort (); Console.log (arraylist.tostring ());//1,2,3,4,5

The concept of heap sequencing is not difficult to understand, the only thing to pay attention to is the concept of heap data structure, I hope I said clearly, if you think I do not elaborate on the heap, first you can Baidu, and then you can Google, again you can go to search Wikipedia. Not really, you go here to see This is one of a series of tutorials related to Java. Of course, even if you do not understand Java, I believe you can also understand, really, I am not joking.

I am struggling to draw a picture or end it, because it really takes time to draw a complete flowchart ... I smoke a cigarette and think about it. Why don't you go and buy a book? Well.... A good suggestion.

Below we use the array [3,5,1,6,4,7,2] as the basic data for the legend:

Pictures to be combined with the code to see, or can not understand the oh .... Also, this diagram you better enlarge the look, otherwise tired eyes ...

Finally, there are a lot of sorting algorithms, such as counting sorting, bucket sorting, cardinal sorting and so on. Sorting algorithms are much more than that. But this series does not introduce so many algorithms, if you want to go deeper to understand the content of other algorithms, you can find the relevant information yourself.

Well, finally to the end, I hope the content of this article can bring you a little bit of harvest.

Finally, because my level is limited, the ability and the great God is still very far apart, if there are errors or unclear, but also hope that everyone is not hesitate to correct. Thank you so much!

The first glimpse of JS algorithm 02 (Sort algorithm 02-merge, Fast and heap sort)

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: 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.