The first glimpse of JS algorithm 01 (Sort algorithm 01-bubbling, selecting, inserting)

Source: Internet
Author: User

Sort of, I think we must have experienced or are experiencing. Perhaps you do not know the algorithm, the sorting algorithm is ignorant, but you must use some third-party library API to sort by one click, then, when you enjoy the convenience of the same time, you have to think about how it is the bottom of how it is implemented? Is this the best way to implement the algorithm? Is there any other possibility to achieve a faster sequencing? Well, hopefully after this article. For the sorting algorithm, you will no longer feel strange and confused.

This article will introduce some simple and commonly used sorting algorithms, such as our familiar bubbling sort, and select sort, insert sort, merge sort, etc. Of course, once you have learned the implementation of these algorithms in JS, you can actually understand the algorithm. Even if you want to implement these algorithms in other languages later, it's just a matter of language features.

We specialize in writing an array class and adding a variety of sorting algorithms to it. So, let's start with a simple shelf.

function ArrayList () {    var array = [];      This function (item) {        Array.push (item);    };      This function () {        return  array.join ();    };}

We build an array class, and there is only one insert and ToString method so we can enter array elements and print array elements.

Here we add a variety of sorting methods for this array class. Let's start with the simplest.

1. Bubble sort

The bubble sort is simple enough to compare any two adjacent elements in the array, and if the first one is larger than the second, then the position of the two elements is exchanged. In this way, the larger element will move 1.1 points to the correct position, just as the bubbles rise to the surface. Let's take a look at the code first.

//A method that swaps two adjacent elements in an array, passing in adjacent arrays, and subscripts of adjacent two elements. varSwap =function(array,index1,index2) {//here, is the most "ordinary" way to store the index1 element through an intermediate amount, because to set the value of Index1 to Index2, and then set the value of Index2 to the AUX variable that just stored index1.     //I hope I have said it clearly enough.     varAux =ARRAY[INDEX1]; ARRAY[INDEX1]=Array[index2]; ARRAY[INDEX2]=aux; //but we can have a simpler way of replacing the position of two array elements.     //one is the following new method of ES6. The deconstruction assignment of the array. Not much to say, we can go to see for themselves.     //[ARRAY[INDE1],ARRAY[INDEX2]] = [ARRAY[INDEX2],ARRAY[INDEX1]];    //Another method is to use the splice method of the array, delete the two elements starting from index1, and insert index2 in the deleted position, and INDEX1 has achieved the purpose of replacing the element.
If you are not very clear on the array method, see here with JS to implement those data structure 02 (array of 02-array method)
   //Array.splice (Index1,2,array[index2],array[index1]);}; //This is the simplest and, of course, the slowest sort method, and we need a two-layer loop to judge the worth of the size, so as to step by step to determine each worthwhile location. //here I'm going to ask why the outer loop (i) loops around the length of the array element, and the inner layer (j) is 1 less than the length of the array. //because this is the minimum number of cycles that can be guaranteed to be compared for every two elements, it is not believed that you have increased the number of two cycles (length +100000); To try and find the results are still what we want. (Of course, this is more time-consuming.) )//but you reduce the number of times less, and the result of the order is not right (in fact, here can be reasonable to reduce the number of inner loop, said later). You can also understand that the outer loop controls how many numbers we have to compare, the inner loop to the specific operation two number of comparisons. This. Bubblesort =function () { varLength =Array.Length; for(vari = 0; i < length; i++) {//i=0,1,2,3,4...length-1; //Console.log (i, "I"); for(varj = 0; J < length-1;j++) {//j = 0,1,2,3,4...length-1-1; //Console.log (J, "J"); if(Array[j] > array[j+1]) {Swap (Array,j,j+1) } } } };//Let's write an easy way to generate an unordered ArrayList. This method is outside of the constructor function. You don't have to. Just to make it easier to generate an array. functioncreatarraylist (size) {varArray =NewArrayList (); for(vari = size; i > 0; i--) {Array.insert (i); } returnArray;}varArrayList = Creatarraylist (5); Console.log (arraylist.tostring ());//5,4,3,2,1Arraylist.bubblesort (); Console.log (arraylist.tostring ());//1,2,3,4,5

I believe the above explanation is enough, let's take a look below to see if we can improve the efficiency of this waste time-consuming bubble sort, let's improve a little bit of performance on the basis of simple implementation?

//let's look at the difference between the Modifiedbubblesort and the Bubblesort, the only difference is that the inner loop is more than one I in the second condition of the For loop. What is the purpose of this?     //Let's get this point out at 1.1. Suppose our array is "5,4,3,2,1", when i = 0 (the first outer loop), we take 5 to compare with 4,3,2,1, and the last array is gradually changed to "4,3,2,1,5";    //at this point, 5 is the largest, when I=1 (the second outer loop). At this point our inner loop is no longer required to take the current J to compare with 5 (that is, the largest of the arrays determined).     //Each time the outer layer is looped, each element in the interior is exchanged for a position (if one is met), and eventually each inner loop is completed, determining a value that is the largest of the current number of wheels.     //so since we already know what the maximum value is, we don't have to do it again in the number of loops that follow. This will improve the efficiency of our execution.     //here again a few more mouths, when i = 0 o'clock, j = 0,j < length-1-0; When i = 1 o'clock, j = 0,j < length-1-1; (to understand this phrase)     This. Modifiedbubblesort =function () {        varLength =Array.Length;  for(vari = 0; i < length; i++) {             for(varj = 0; J < length-1-i;j++) {                if(Array[j] > array[j+1]) {Swap (Array,j,j+1); }            }        }    };

Improved bubble sequencing we've learned it, but it's the only way. There is no way to further optimize and improve efficiency. Bubble sort, is the most basic and least recommended sort method. Because of its time complexity is O (n2), large o notation, we will explain in detail what is the large O notation in later content. It can be tentatively understood here that the two-layer cycle forms the result of I*j, which is the total number of cycles of length*length. That is N2. (This is actually the case). If it's a three-layer loop, it's probably the complexity of O (N3).

2. Select Sort

  The idea of sorting is to find the smallest value in the data structure and put it in the first place, then find the second smallest value, put it in the second place, and so on. (You can also find the maximum value for the last one, of course). Let's still look at the code.

//in fact, the choice of sorting is not complicated, let's take a look.  This. Selectionsort =function () {    //First, we declare a variable that stores the length of the array, and a variable that stores the current minimum value, oh no, the corresponding subscript variable that stores the current minimum value.     varLength =array.length,indexmin; //In the outer loop, the number of cycles is the length of the entire array.      for(vari = 0; i < length-1; i++) {        //here, at the beginning of the cycle we do not know who is the smallest, so we put the first worthy subscript as the smallest worthy subscript. Indexmin =i; //Inner Loop, we compare the current minimum value (that is, the value of indexmin) and the other values in the array in turn.         //here, why is J=i?         //each time we have an outer loop, we will determine a minimum value and place the minimum value in the corresponding position (starting with subscript 0 each time the outer loop is added 1).         //then we do not need to compare the start cycle over the comparison of the subscript, so we each time after the outer loop, the inner layer of the loop from the position of the start can be.         //somewhat similar to Modifiedbubblesort's j<length-1-i;         for(varj = i; J < length; J + +) {            //In this way, we can determine what the minimum value is, if the corresponding value of the indexmin is greater than the value corresponding to J, the minimum value corresponding to the subscript should be J.             if(Array[indexmin] >Array[j]) {Indexmin=J; }        }        //At the end of the outer loop, if I (the minimum value we determined at the beginning) is not equal to indexmin. This indicates that I is not the minimum value. We're going to swap two values for a position.         //If it is equal, the current indexmin is the minimum value and no swap position is required. Console.log (i,indexmin)if(I!==indexmin) {Swap (array,i,indexmin) }}};

But the complexity of choosing sorting is also O (N2), and the efficiency is not very good. So let's keep looking down.

3. Insert Sort

Insert sort, how to say .... is to assume that the first element in the array is already sorted (not assuming no, or that it is ordered, because it is an element), then we compare with the second element, the second element should be before the first element, or in the original position do not move it? That is, the first element and the second element compare the size to determine the position of the two elements. So, just the first two items of the array elements, they are in the right order. Then we compare the third element with the first two elements to determine where the third element should be inserted in the first two elements.

To put it simply, we can assume that there is a sorted subarray in the sorted array, which we then compare with the elements in the sub-array, in turn, to determine where the subsequent elements should be inserted into the sub-array. Finally, we will get a fully sorted array.

We continue to look at the code.

 This. Insertionsort =function () {    //J and temp are used to store the current subscript and the value corresponding to the current subscript.     varLength =array.length,j,temp; //Why does I have to start from 1? Because the element with index 0 is considered to have been sorted.      for(vari = 1; i < length; i++) {        //we use J to store the subscript of the value currently being compared, which is I, because the elements on the 0 have already been sorted (we do this by default). j =i; //again, we want to compare the value of the current index to determine if it needs to be swapped, so we also have a variable that temporarily stores the values of the current subscript. temp =Array[i]; //If the j>0 description is an element in the array,        //also, if the previous element (J-1) of J (i) is larger than the current variable, then the value of J (i) is set to the value of j-1, that is, the position of J (i) is shifted backward.         //until array[j-1] > temp is false. Why not say j>0 this condition? Because this is a protective layer that guarantees the correct contrast of the array, it is, of course, very important.         //here is a very necessary and important point, which is the question of the value of our variable J.         //we are looping until the condition does not come out of the loop, where J is the place where the value of temporary storage array[i] (that is temp) needs to be inserted.         //because we are in the while loop, each loop uses j--to move the subscript position a little bit forward, until the condition is not established, and we get a J where the temp should be inserted.          while(J > 0 && array[j-1] >temp) {Array[j]= Array[j-1]; J--; } Array[j]=temp; }};

The above code is the insertion sort, in which the points to note are in the while loop, which takes a little thought to understand. I'm simply saying that in the code, we declare that the J and temp variables are used to store the current subscript and its corresponding value. So the role of temp is that we can find out where the insertion is, what the value should be inserted, and the meaning of J's existence is to determine where the position is. So, we're going to compare the previous one to temp in the while loop with the value of the descending j, and if that's the case, then I'm going to move backwards, knowing that it's not moving (while the condition of the while loop does not match), we find the J that should be inserted in the temp position. It's time to insert temp in that position.

  

So, the simple sort method is introduced here, the next chapter we look at the more complex, but more efficient sorting algorithm.

In fact, I am writing this article, has been struggling to draw pictures, so that everyone can more easily understand the code and the implementation of these sorting algorithms, but I searched the internet. A whole bunch!! So, I think it's okay. However, I have attached the relevant link address, which has a more detailed explanation of the concept of the algorithm.

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 01 (Sort algorithm 01-bubbling, selecting, inserting)

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.