A fast sorting method of JavaScript Realizing In-place thought _javascript skills

Source: Internet
Author: User
Tags benchmark

Quick sort, also called dividing exchange sort. A fast sorting algorithm based on the method of divide and conquer.

This paper is mainly about the use of JavaScript to achieve the rapid ordering of in-place ideas

Divided by the rule of law:

In computer science, the divide-and-conquer method is a very important algorithm model based on multiple branch recursion. The literal explanation is "divide and conquer", which is to divide a complex problem into two or more identical or similar child problems until the last child problem can be directly solved, the solution of the original problem is the merging of the solution of the child problem. (Excerpt from Wikipedia)

The idea of a quick sort

Array to specify an element as a ruler, which is larger than it is placed behind the element, before it is placed in front of the element, and so repeats until all positive orders are arranged.

The quick sort is divided into three steps:

Selection datum: Select an element in the data structure as the benchmark (pivot)

Division: Reference to the size of the datum element value, divided into unordered areas, all data less than the datum element into an interval, all the data larger than the datum into another interval, after the partition operation, the base element position is the final sort where it should be located

Recursion: The algorithm that recursively calls steps 1th and 2nd for the first two unordered intervals, until all unordered intervals are left with only one element.

Now let's talk about the universal implementation (no use of the in-situ algorithm)

function QuickSort (arr) {if (arr.length <= 1) return;//take the array closest to the median datum, odd and even values are different, but not impressive, of course, you can select the first, or the last number as the benchmark,
There is no excessive description of var Pivotindex = Math.floor (ARR.LENGTH/2);
var pivot = Arr.splice (pivotindex, 1) [0];
The left and right intervals, used to store the sorted number on the "var" right = [];
var right = [];
Console.log (' benchmark: ' + pivot + ' time '); for (var i = 0; i < arr.length; i++) {console.log (' partition operation's first ' + (i + 1) + ' sub-loop: ');///Less than datum, placed in left interval, greater than datum, placed in right interval if (Arr[i] & Lt Pivot) {Left.push (Arr[i]) Console.log (' Left: ' + (Arr[i])}} else {Right.push (arr[i)); Console.log (' Right: ' + (Arr[i])}}/ /here Use the concat operator to stitch the left interval, datum, and right interval into a new array//and then recursively 1,2 steps until all the unordered intervals are left with only one element, recursive end return quickSort. Concat ([pivot],
QuickSort (right));
} var arr = [14, 3, 15, 7, 2, 76, 11];
Console.log (QuickSort (arr));
/* The benchmark is 7 o'clock, the first partition gets about two subsets [3, 2,] 7 [14, 15, 76, 11]; * with a benchmark of 2, the left subset [3,2] is sorted by partition and obtained [2] 3. Left subset sort all ends * with a datum of 76, the right subset is divided into the sorting area, get [14, 15, 11] 76 * At this time to the top [14, 15, 11] with a datum of 15 to divide the district sort again, [14, 11] 15 * At this time to the above [14, 11] with the benchmark for 11 again Sort by partition, 11 [14] * All unordered intervals are left with only one element, recursive end * * * * *

The result can be obtained by debugging the breakpoint.

Disadvantages:

It requires an additional storage space of Ω (n), which is as bad as the merge sort. In a production environment, additional memory space is required to affect performance.

At the same time, many people think that the top is the real quick sort. So, in the following, it is necessary to recommend a quick sort of in-place algorithm

There are about the algorithm can refer to Wikipedia, by the wall of the classmate, Baidu is also similar.

In-place

Fast sorting is generally implemented by recursion, the most key is the partition partition function, it divides the array into two parts, one part is less than pivot, and the other part is larger than pivot. The specific principle mentioned above

 function QuickSort (arr) {//Swap function swap (arr, A, b) {var temp = Arr[a]; Arr[a] = arr[b]; arr
[b] = temp; }//partition function partition (arr, left, right) {/** * When the final pivot is not known at the beginning of the storage location, you can first pivot exchange to the back of * here directly define the rightmost element as the benchmark * * var pivot = AR
R[right];
/** * Storage of elements less than pivot, is next to the previous element, otherwise the gap may be more than the pivot element, * So declare a storeindex variable, and initialized to left in order to store less than the pivot element.
* * var storeindex = left; for (var i = left < right; i++) {if (Arr[i] < pivot) {/** * traverse the array to find elements that are less than pivot (the elements that are larger than the pivot will skip) * will loop through the elements of the time I get
Swap is placed at Storeindex, * and the Storeindex is incremented by 1 to indicate the next possible swap position/swap (arr, storeindex, i);
storeindex++;
}//finally: Swap pivot to Storeindex, where the benchmark element is placed to the final correct position swap (arr, right, storeindex);
return storeindex; function sort (arr, left, right) {if [left > right] return; var storeindex = partition (arr, left, right); sort (arr, l
EFT, storeIndex-1);
Sort (arr, Storeindex + 1, right);
Sort (arr, 0, arr.length-1);
return arr; } console.log ([8, 4, 8, QuickSort, 1, num]); 

Optimization of partitions

Here the careful schoolmate may propose, chooses the different datum, whether will have the different performance performance, the answer is affirmative, but, because, I was engaged in the front end, to the algorithm is not very understanding, therefore, this pit leaves the formidable person to fill.

Degree of complexity

Fast sorting is the fastest algorithm for sorting, its time complexity is O (log n)

In average, sort n items to be 0 (n log n) times compared. In the worst case, 0 (n2) comparisons are required.

https://github.com/LYZ0106/

The above is a small set of JavaScript to introduce the implementation of the In-place thought of the fast sorting method, I hope to help you, if you have any questions welcome to my message, small series will promptly reply to everyone, here also thank you for your support cloud Habitat community!

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.