Today's studio off the net! Decisively back to the dorm, otherwise all kinds of information are not. (he says he'll find it in the future!) Sorry, it's humming again. Enter the theme, we all know, the fast line is a variety of sorting algorithms, the most efficient is the most widely used, there is more important point, interview special Love Test!
In fact, we have heard about the fast row, that is, first take out a benchmark value, and then the other number with the comparison, small put on the left side of the set, large put on the right of the set, and then repeated through the recursive step to achieve the most efficient quicksort.
Talk was cheap, show you my code!
Sorting results I will not write it out, we will count the size, ha ha.
Just finished the JavaScript quick Platoon, suddenly thought, Array.prototype.sort, does not have a sorting method? Of course, the use of the sort method is a disadvantage, such as the number of the group, the printed result can be:
Well! Sort of the pit-daddy string! To speak quickly, the sort function can receive a comparison function parameter, and if a negative number is returned, it is preceded by a positive return. We look directly at the simplest kind of contrast function!
Ok! Ascending or something, absolutely!
Both methods have come out, in the spirit of choosing difficult to be unable to have the mind (the time to install force!) , we have to know if it's fast, or the sort speed of the native array object. (That's no nonsense!) Native optimization is definitely faster than custom recursion! )。 Well, let's see how fast it is.
Test environment: 10,000 random 0~10 numbers are sorted.
Test procedure:
vararr = [];/*10,000 Random Numbers*/ for(varn = 0; n < 10000; n++) {Arr.push (Math.Round (Math.random ()*10));}varText =function(FN, param) {varstart, end; //record the start time of executionStart =NewDate (). GetTime (); //Execute the method you want to testArr.quicksort () or arr.sort (compare); //record the end time of the executionEnd =NewDate (). GetTime (); //output The results of the method to be tested and time consumingConsole.log ("Sort done, time consuming" + (End-start) + "milliseconds" );} Text ();
First QuickSort sort of test: using Arr.quicksort ()
Roughly 2250ms in the vicinity of fluctuations, 10K data sorting, 2S.
And then to the native sort Sort method test: Using Arr.sort (Compare)
10ms .....
230 times times the gap!
Everyone obediently use sort bar, nothing but write a compare function, how big things!
hahaha, this morning off the net, on their own churn get some of this, the evening hair.
Recently my blog important code will be based on PO, in fact, in order to let the audience master, can personally hand code, do not hand.
If there is any mistake, please point out immediately, I will revise as soon as possible, so as not to mislead others oh Oh!
JavaScript quick and native sort test