Fast Sort algorithm JavaScript implementation

Source: Internet
Author: User

    1. function Quicksort (arr) {
    2. function Q (start,end) {
    3. if (start>=end) {return;}
    4. var pivot = start,
    5. temp = Arr[pivot],
    6. i = start+1;
    7. for (; i<=end;i++) {
    8. if (arr[i]<temp) {
    9. var s = arr.splice (i,1) [0];
    10. Arr.splice (start,0,s);
    11. pivot++;
    12. }
    13. }
    14. Q (start,pivot-1);
    15. Q (pivot+1,end);
    16. }
    17. Q (0,arr.length);
    18. return arr;
    19. }
    20. var arrs = [9,45,45,90,3,77,4,90];
    21. var c = quicksort (ARRS);
    22. Console.log (c);

if (start>=end) {return;} in line 3rd, I consider this way of quitting recursion.

When there are two items left in the Subarray, two scenarios are analyzed:

(1) When the first sub-array (passed to the parameter start) is smaller than the second item (passed to the parameter end)

In the function q the first adjustment is made, the last variable start points to the first item, the variable pivot points to the first item, and then:

Q (start,pivot-1);//At this time Start==pivot, so start>pivot-1, through if (start>=end) {return;} Exit recursion

Q (pivot+1,end);//At this time pivot+1==end, the same as exit recursion

(2) When the first item is larger than the second

In function q, make the adjustment again, the last variable start points to the first item, the variable pivot points to the second item, and then:

Q (start,pivot-1);//start==pivot-1 at this time, exit recursion

Q (pivot+1,end);//At this time pivot+1>end; also exits recursion

Fast Sort algorithm JavaScript implementation

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.