JS Implementation Quick Sort (in-place) brief

Source: Internet
Author: User
Tags benchmark

Quick sort, also called divide-and-trade sorting. A fast sorting algorithm based on divide-and-conquer method is implemented.

This paper mainly discusses the use of JavaScript to realize the rapid sequencing of In-place thought

Divide and conquer law:

in computer science, divide-and- conquer method is a very important algorithm paradigm based on branching recursion. The literal interpretation is "divide and conquer", that is, to divide a complex problem into two or more identical or similar sub-problems, until the last sub-problem can be simply solved directly, the solution of the original problem is the solution of the sub-problem of the merger. (excerpt from Wikipedia)

The idea of quick sequencing

An element in an array is specified as a ruler, larger than it is placed behind the element, smaller than it is placed before the element, and so repeated until all are ordered.

Quick sorting is in three steps:

    1. Benchmark: Select an element in the data structure as a datum (pivot)
    2. Partitioning: Referencing the size of the datum element value, dividing the unordered area, all data that is less than the datum element into an interval, all data that is greater than the datum element into another interval, the position of the datum element at the end of the partition operation is where it should be after the final sort.
    3. Recursion: For the first division of the two unordered interval, recursively call the algorithm of step 1 and step 2 , until all the unordered interval has only one element left.

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

function QuickSort (arr) {if(Arr.length <= 1) return ; //take the array closest to the middle of the digital datum, odd and even values are different, but not the impression, of course, you can choose the first, or the last number as the benchmark, there is no too much descriptionvar pivotindex = Math.floor (arr.length/2); var pivot= Arr.splice (Pivotindex, 1) [0]; //left and right intervals, for storing the number after sortingvar left = []; var right= []; Console.log (' Benchmark for: ' + pivot + ' when ');  for(var i = 0; i < arr.length; i++) {Console.log (' Partition operation ' + (i + 1) + ' Secondary cycle: '); //less than the reference, placed in the left interval, greater than the benchmark, placed in the right interval        if(Arr[i] <pivot)            {Left.push (arr[i]); Console.log (' Left: ' +(Arr[i])} Else{Right.push (arr[i]); Console.log (' Right: ' +(Arr[i])} }    //here, the concat operator is used to stitch the left interval, datum, and right intervals into a new array//then pass the steps until all the unordered intervals are left with only one element, ending with recursion.    returnQuickSort (left). Concat ([pivot], QuickSort (right));} var arr= [14, 3, 15, 7, 2, 76, 11];console.log (QuickSort (arr));/** Baseline is 7 o'clock, the first partition to get left and right two subsets [3, 2,] 7 [14, 15, 76, 11]; * With a datum of 2, the left subset [3,2] is sorted to get [2] 3. Left subset sort all end * with a datum of 76, the subset on the right is sorted, get [14, 15, 11] 76 * At this time to the above [14, 15, 11] with a benchmark of 15 and then the division of the sorting, [14, 11] 15 * At this time to the above [14, 11] with the benchmark 11 again To sort the divisions, 11 [14] * All unordered intervals have only one element left, recursive end **/

The result can be obtained by debugging the breakpoint.

Disadvantages:

It requires an extra storage space of Ω (n), just 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 fast sort. So, in the following, it is necessary to recommend the fast sequencing of the in-place algorithm

There is a reference to the in-situ algorithm can refer to Wikipedia, the wall of students, Baidu is similar.

In-place

The fast sort is usually implemented by recursion, the most important is the partition partition function, which divides the array into two parts, part is smaller than pivot, and the other part is larger than pivot. Specific principles mentioned above

functionQuickSort (arr) {//Exchange    functionswap (arr, A, b) {vartemp =Arr[a]; Arr[a]=Arr[b]; ARR[B]=temp; }    //Partitioning    functionpartition (arr, left, right) {/** * At the beginning, I do not know where the final pivot is stored, you can first switch pivot to the back * here directly define the rightmost element as the benchmark*/        varPivot =Arr[right]; /** * When storing elements smaller than pivot, it is next to the previous element, otherwise the void may be larger than the pivot element, so declare a storeindex variable and initialize it to left to hold the element less than pivot next to each other. */        varStoreindex =Left ;  for(vari = left; I < right; i++) {            if(Arr[i] <pivot) {                /** * Iterate through the array to find elements less than pivot, (elements greater than pivot will be skipped) * The elements that are obtained when the loop I times are placed in the Storeindex place by swap swap, * and increments of storeindex by 1, indicating the next possible location to swap*/swap (arr, storeindex, i); Storeindex++; }        }        //finally: Swap pivot to Storeindex where the datum element is placed in the final correct positionswap (arr, right, storeindex); returnStoreindex; }    functionsort (arr, left, right) {if(Left > right)return; varStoreindex =partition (arr, left, right); Sort (arr, left, Storeindex-1); Sort (arr, storeindex+ 1, right); } sort (arr,0, Arr.length-1); returnarr;} Console.log (QuickSort ([8, 4, 90, 8, 34, 67, 1, 26, 17]));

Optimization of partitions

Here the careful classmate may propose, choose different benchmarks, whether there will be different performance, the answer is yes, but, because, I was engaged in front-end, the algorithm is not very understanding, so, this pit left to the serious people to fill.

Complexity of

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

On average, sort n items to 0 (n log n) comparisons. In the worst case scenario, a 0 (n2) comparison is required.

JS Implementation Quick Sort (in-place) brief

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.