Quick ordering of JavaScript recursion

Source: Internet
Author: User
Tags javascript array

1. Quick Sorting ideas

(1) In the dataset, select an element as the "datum" (pivot).

(2) All elements smaller than "datum" are moved to the left of "datum", and all elements that are greater than "datum" are moved to the right of "datum".

(3) for the two subsets to the left and right of the Datum, repeat the first and second steps until there is only one element left in all the subsets.

2. Digital array sequencing Step analysis

(1) original array [23,4,16,49,34,86,801]

(2) Determine the middle position, the original array is divided into half [23,4,16,34] 49 [86,801]

(3) The left half and the right half of the array to do the above Operation 4 [23,16,34] 49 86 [801]

(4) Repeat Part III 4 16 [23,34] 49 86 801

(5) 4 16 23 [34] 49 86 801

(6) 4 16 23 34 49 86 801

3. Implementation of JavaScript based on recursive thinking

function QuickSort (arr) {  if (arr.length <= 1) {    ///length less than 1 returns directly to    arr;  }  var pivotindex = Math.floor (ARR.LENGTH/2);    Rounding up, take the middle position  var pivot  = Arr[pivotindex]; Take the middle value  var less = array (), greater = Array (), and for (var i = 0; i < arr.length; i++) {    if (i!=pivotindex) {if (Arr[i] >= pivot)  {              greater. Push (Arr[i]);  Right half}else {less              . push (Arr[i]);  Left Half}}}  return QuickSort (less). Concat ([Pivot],quicksort (greater)); Recursive invocation}

Manipulating a JavaScript array can also remove intermediate elements and eliminate the intermediate element directly, so that you can make a few judgments when traversing.

var pivotindex = Math.floor (ARR.LENGTH/2), var pivot = Arr.splice (pivotindex, 1) [0];

  

for (var i = 0; i < arr.length; i++) {if (Arr[i] >= pivot) {              greater. Push (Arr[i]);  Right half}else {less              . push (Arr[i]); Left Half}}

  

Quick ordering of JavaScript recursion

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.