JavaScript common examples of classical algorithms _javascript skills

Source: Internet
Author: User

The examples in this article describe the JavaScript common algorithms. Share to everyone for your reference, specific as follows:

Entry-level algorithm- linear lookup -time complexity O (n)--equivalent to HelloWorld in algorithm boundaries

Linear search (Getting Started HelloWorld)
//a An array, x is the value function to search for
linearsearch (A, x) {for
  (var i = 0; i < a.length; i++) {
    if (a[i] = = x) {return
      i;
    }
  }
  return-1;
}

Two-point search (also known as binary lookup)-Suitable for sorted linear structure-time complexity O (LOGN)

The binary search
//a to an array that has been sorted in ascending order, and X is the
subscript
function BinarySearch (A, x) {
  var low = 0 for the element to be queried//return the target element. a.length-1;
  while (low <= high) {
    var mid = Math.floor (lower + high)/2);//Down Whole   
    if (x = = A[mid]) {return
      mid;
    }
    if (x < A[mid]) {High
      = mid-1;
    }
    else {Low
      = mid + 1;
    }
  }
  return-1;
}

Bubble Sort --time complexity O (n^2)

Bubble sort
Function Bubblesort (A) {for
  (var i = 0; i < a.length; i++) {
    var sorted = true;
  Note: The inner loop is inverted for
    (var j = a.length-1 J > i; j--) {
      if (A[j] < a[j-1]) {
        swap (A, J, j-1);
        sorted = false;
      }
    }
    if (sorted) {return;}}}


Select Sort --time complexity O (n^2)

Select Sort
//train of thought: find the bottom tag of the minimum value, then swap
function Selectionsort (A) {for
  (var i = 0; i < a.length-1; i++) {
    VA R k = i;
    for (var j = i + 1; j < A.length; J + +) {
      if (A[j] < a[k]) {
        k = j;
      }
    }
    if (k!= i) {
      var t = a[k];
      A[K] = A[i];
      A[i] = t;
      println (A);
    }
  return A;
}

Insert Sort --time complexity O (n^2)

Insert Sort
//assuming the elements before the current element have been sorted out, first empty your position,
//And then move backwards in front of the elements larger than yourself until a "pit" is vacated,
//Then insert the target element into the "pit"
function Insertsort (A) {for
  (var i = 1; i < a.length; i++) {
    var x = a[i];
    for (var j = i-1 J >= 0 && a[j] > x; j--) {
      a[j + 1] = A[j];
    }
    if (a[j + 1]!= x) {
      a[j + 1] = x;
      println (A);
    }
  return A;
}

string Reversal --time complexity O (LOGN)

string reversal (e.g., ABC-> CBA)
function Inverse (s) {
  var arr = s.split (');
  var i = 0, j = arr.length-1;
  while (I < j) {
    var t = arr[i];
    Arr[i] = arr[j];
    ARR[J] = t;
    i++;
    j--;
  }
  Return Arr.join (");
}

A conclusion about the ranking of stability :

A simple sort algorithm based on comparison, which is a sort algorithm of O (n^2) with time complexity, is generally considered to be a stable sort
Other advanced sorting algorithms, such as merge sorting, heap sorting, bucket ordering, and so on (usually the time complexity of such algorithms can be optimized to N*LOGN), usually considered to be unstable ordering

single linked list implementation

<script type= "Text/javascript" > Function print (msg) {document.write (msg);
  function println (msg) {print (msg + ' <br/> ');  }//Node class var node = function (v) {this.data = V;//node value this.next = NULL;//Successor Node}//single linked list var singlelink = function () {This.head = new node (null);//Convention header node only placeholder, no value/insert node This.insert = function (v) {var p = th
      Is.head;
      while (P.next!= null) {p = p.next;
    } P.next = new Node (v);
      //Deletes the node at the specified location this.removeat = function (n) {if (n <= 0) {return;
      var prenode = This.getnodebyindex (n-1);
    Prenode.next = PreNode.next.next; 
      ///Take n position node (the Contract head node is No. 0 position)//n is greater than the number of linked list elements, returns the last element this.getnodebyindex = function (n) {var p = this.head;
      var i = 0;
        while (P.next!= null && i < n) {p = p.next;
      i++;
    } return p; ////Query Value v node,//If there are multiple nodes with the same value in the list,//returns the first found THis.getnodebyvalue = function (v) {var p = this.head;
        while (P.next!= null) {p = p.next;
        if (P.data = = v) {return p;
    } return null;
      }//printout all nodes This.print = function () {var p = this.head;
        while (P.next!= null) {p = p.next;
      Print (P.data + "");
    } println ("");
    The duplicate element function Hassamevaluenode (singlelink) {var i = Singlelink.head) is available in the test single chain table L;
      while (I.next!= null) {i = I.next;
      var j = i;
        while (J.next!= null) {j = J.next;
        if (I.data = = J.data) {return true;
  }} return false;
    ///single linked list element inversion function Reversesinglelink (singlelink) {var arr = new Array ();
    var p = singlelink.head;
      Run it first, put all the nodes in the array while (P.next!= null) {p = p.next;
    Arr.push (P.data);
    var NewLink = new Singlelink (); And then traversing the array from the back forward, adding a new list for (var i = arr.length-1 I &Gt;= 0;
    i--) {Newlink.insert (arr[i]);
  return NewLink;
  var linktest = new Singlelink ();
  Linktest.insert (' A ');
  Linktest.insert (' B ');
  Linktest.insert (' C ');
  Linktest.insert (' D ');
  Linktest.print ();//a B C D var newlink = Reversesinglelink (linktest);

 Newlink.print ()//d C B </script>

On the selection of adjacency matrix and adjacency table :

Adjacency Matrix and adjacency table are the basic storage modes of graphs,
in the case of N*n (that is, the remote is less than the vertex), the adjacent table storage is more suitable for (relative to the matrix, the adjacency table stores only the edges and vertices of the value, do not store null value, storage efficiency is higher)
dense diagram in the case (that is, remote ground vertex), with the adjacency matrix storage is more suitable for (more data, to do traversal, if the linked list storage, often jump to jump, inefficient)

Heap:

almost complete two-forked tree : A two-prong tree that may be missing from one or several leaves on the far right . On physical storage, arrays can be stored, and if the vertices of a[j] have left and right child nodes, then the left node is a[2j] and the right node is a[2j+1],a[j] The parent vertex is stored in A[J/2]

Heap: itself is an almost complete two-fork tree, and the value of the parent node is not less than the value of the child node . Scenario: Precedence queues, looking for the maximum or second maximum value, and inserting a new element into the priority queue.

Note: The following are all the discussed heaps, where the elements of the Convention index 0 are occupied and the valid elements start with subscript 1

Depending on the definition of the heap, you can test whether an array is a heap by using the following code:

Tests whether array H is heap
//(Contract valid element starts with subscript 1)
//Time complexity O (n)
function isheap (H) {
  if (h.length <= 1) {return false;}
  var half = Math.floor (H.LENGTH/2); According to the nature of the heap, only half of the cycle limit is sufficient for
  (var i = 1; I <= half; i++) {
    //If parent node, more than any child node is small, that is, violating the heap definition
    if (H[i] < h[2 * I] | | H[i] < H[2 * i + 1]) {return
      false;
    }
  }
  return true;
}

Node up adjustment siftup

In some cases, if the value of an element in the heap changes (for example, after 10,8,9,7 becomes 10,8,9,20, 20 needs to be adjusted upwards), no longer satisfies the definition of the heap and needs to be adjusted upwards, you can use the following code to implement the

The nodes in the heap move Up
//(the convention valid element starts with subscript 1)
function Siftup (H, i) {
  if (I <= 1) {return
    ;
  }
  for (var j = i; j > 1; j = Math.floor (J/2)) {
    var k = Math.floor (J/2);
    found that the child node is larger than the parent node, then swap the position with the parent node
    if (H[j] > H[k]) {
      var t = h[j];
      H[J] = h[k];
      H[k] = t;
    }
    else {
      //description already conforms to the heap definition, adjust end, exit return
    }
}}

The node adjusts the Siftdown (since there is upward adjustment, there is a downward adjustment naturally)

The nodes in the heap Move Down
//(contract valid elements start with subscript 1)
//Time complexity O (logn)
function Siftdown (H, i) {
  if (2 * i > H.length) {//leaf node, You don't have to move down again.
  for (var j = 2 * i; j < H.length J = 2 * j) {
    //positioning J to the larger of two sub nodes (very ingenious)
    if (h[j + 1] > H[j]) {
      J + +;
    }
    var k = Math.floor (J/2);
    if (H[k] < h[j]) {
      var t = h[k];
      H[K] = h[j];
      H[J] = t;
    }
    else {return
      ;
    }
  }
}

Adding new elements to the heap

add element x
//Time complexity O (logn)
function Insert (h, x) {
  //Train of thought: First add the target element x
  H.push (x) to the array;
  Then push up
  siftup (H, h.length-1);
}

Removing elements from the heap

Delete element
//Time complexity O (logn)
function Remove (h, i) {
  //Train of thought: first position I element and last position element N Exchange
  //Then data length minus 1 ( So I'm going to get rid of the elements of the I position, but the whole heap is destroyed)
  //need to make a decision: The last element n needs to be adjusted upward, or downward adjustment
  //basis: for example, larger than the original element of the position, then the upward adjustment, conversely downward adjustment
  var x = h[i] ; First the original I position of the elements to protect///put the
  last element to the I position
  //At the same time delete the last element (JS language superiority embodiment!)
  H[i] = H.pop ();
  var n = h.length-1;
  if (i = = = n + 1) {
    ///If the removal is exactly one of the last two elements,
    //No need to adjust return
    ;
  }
  if (H[i] > x) {
    siftup (H, i);
  }
  else {
    Siftdown (H, i);
  }
}
Removes the maximum//
return maximum
//Time complexity O (logn)
function Deletemax (H) {
  var x = h[1]
  from the heap; Remove (H, 1);
  return x;
}

Heap Sort :

This is a very ingenious sort of algorithm, the essence is to make full use of the "heap" the characteristics of the data structure itself (the first element is necessarily the largest), and each element of the move up, down, the time of the second degree is relatively low, only O (Logn), space, also without the use of additional storage space, You can only exchange elements within the array itself.

Ideas:

1, first the first element (that is, the largest element) with the end of the swap---the purpose is to sink the maximum value, the next round of weight will no longer control it
2, after 1, the remaining elements are usually no longer a heap. At this time, as long as the new first element with Siftdown down, after adjustment, the new maximum elements of natural rise to the first element of the position of the
3, repeated 1, 2, the large elements of the bottom of each one, and finally the entire array ordered.
Time complexity Analysis: Creating a heap at the cost of O (n), each siftdown cost O (logn), adjusting up to n-1 elements, so the total cost is O (n) + (N-1) O (Logn), and the final time complexity is O (NLOGN)

The node in the heap moves down//(the contract valid element starts at subscript 1)//i The index of the element to be adjusted//n the subscript range upper value//Time complexity O (logn) function Siftdown (H, I, N) {if (n >= h.l
  Ength) {n = h.length;
  if (2 * i > N) {//leaf node, there is no need to move back again;
    for (var j = 2 * i; j < n; j = 2 * j) {//positioning J to the larger of two sub nodes (very ingenious) if (H[j + 1] > H[j]) {j + +;
    var k = Math.floor (J/2);
      if (H[k] < h[j]) {var t = h[k];
      H[K] = H[j];
    H[J] = t;
    else {return;
  }}///The first n elements of an array to create the operation function of the heap makeheap (A, N) {if (n >= a.length) {n = a.length;
  for (var i = Math.floor (N/2); I >= 1; i--) {Siftdown (A, I, N);
  Stack sort (not in descending order)//Time complexity O (nlogn) function heapsort (h) {//First build heap Makeheap (h, h.length); for (var j = h.length-1 J >= 2; j--) {//The first element must be the largest//swap the largest element with the last element,//The maximum element will sink, the next round no longer consider var x = h[1]
    ;
    H[1] = H[j];
    H[J] = x; After the swap, the remaining elements are no longer satisfied with the heap definition,////The new first element is lowered (so as to maintain the "shape" of the heap)//After the adjustment, the maximum value of the remaining elements must float to the first/second round
    Siftdown (H, 1, j-1);
return H;

 }

About building a heap, if you understand the principle, can also reverse thinking, and vice versa

function MakeHeap2 (A, n) {
  if (n >= a.length) {
    n = a.length;
  }
  for (var i = Math.floor (N/2); I <= n; i++) {
    Siftup (A, i);
  }
}

Do not intersect collection lookup, merge

Defines node nodes class
var node = function (V, p) {
    this.value = V;//node's value
    this.parent = p;//node's parent
    This.rank = 0; /node rank (default is 0)    
}
//Find root node containing node x var found 
= function (x) {
    var y = x;
    while (y.parent!= null) {
      y = y.parent;
    }
    var root = y;
    y = x;
    "Path Compression"
    while (y.parent!= null) along X to root {
      //Save the parent node first, otherwise the next line is adjusted, the
      var w = y.parent is lost;
      Hang the target node under the root
      y.parent = root;
      Again, restore the work pointer to the original parent node of the target node,
      //continue to compress up and down the
      y = w
    } return
    root;
}
Merge node x,y corresponding two tree
//Time complexity O (m)-M for a subset to be merged the sum of the
var union = function (x, y) {
    ////////= Find the root of the set of X-
    var u = found (x);
    //Again find the root of the Y-owning set of
    var v = found (y);
    The rank small set is hung on the set of rank
    if (U.rank <= v.rank) {
      u.parent = v;
      if (U.rank = = V.rank) {
        //Two A set of rank Briber//
        give the "wins" a bit of reward, rank+1
        V.rank + + 1;
      }
    else {
      v.parent = u;
    }
}

Inductive method :

Let's take a look at the recursive implementation of two sorts

A recursive implementation
//invocation example for selecting a sort: Selectionsort ([3,2,1],0)
function Selectionsortrec (A, i) {
  var n = a.length-1;
  if (I < n) {
    var k = i;
    for (var j = i + 1; j <= N; j + +) {
      if (A[j] < a[k]) {
        k = j
      }
    }
    if (k!= i) {
      var t = a[k ];
      A[K] = A[i];
      A[i] = t;
    }
    Selectionsortrec (A, i + 1);
  }
Insert sort Recursive implementation
//Invocation Example: Insertsortrec ([4,3,2,1],3);
function Insertsortrec (A, i) {
  if (i > 0) {
    var x = a[i];
    Insertsortrec (A, i-1);
    var j = i-1;
    while (J >= 0 && A[j] > x) {
      a[j + 1] = A[j];
      j--;
    }
    A[j + 1] = x;
  }
}

Recursive programs are usually easy to understand and code easy to implement, and look at two small examples:

From the array, find the maximum value

Find the maximum value in the array (recursive implementation)
function Findmax (A, i) {
  if (i = = 0) {return
    a[0];
  }
  var y = Findmax (A, i-1);
  var x = a[i-1];
  Return y > x? y:x;
}
var A = [1,2,3,4,5,6,7,8,9];
var test = Findmax (a,a.length);
alert (test);//Return 9

There is an array that has been sorted in ascending order, checking that there are two numbers in the array, and that their and exactly is X?

5.33 Recursive implementation
//a to [1..N] ordered array
//x for test and
//If there are two numbers and X, return True, otherwise return false
function sumx (A, I, J , x) {
  if (i >= j) {return
    false;
  }
  if (A[i] + a[j] = = x) {return
    true;
  }
  else if (A[i] + a[j] < x) {
    //i back return
    sumx (A, i + 1, j, x);
  }
  else {
    //j move forward return
    sumx (A, I, j-1, x);
  }
var A = [1, 2, 3, 4, 5, 6, 7, 8];
var test1 = sumx (a,0,a.length-1,9);
alert (test1); Returns True

Although the recursive program is clear, but usually inefficient, generally speaking, recursive implementation, can be written as a recursive implementation, the above code can also be written:

5.33 Non-recursive implementation
function sumX2 (A, x) {
  var i = 0, j = a.length-1;
  while (I < j) {
    if (A[i] + a[j] = = x) {return
      true;
    }
    else if (A[i] + a[j] < x) {
      //i move
      i++ later;
    }
    else {
      //j forward
      j--;
    }
  }
  return false;
}
var A = [1, 2, 3, 4, 5, 6, 7, 8];
var test2 = sumX2 (a,9);
alert (test2);//return True

Recursion does not always represent inefficiency, in some scenarios, the efficiency of recursion is higher, such as the calculation of the M-power X, the conventional algorithm requires m multiplication, the following algorithm, but the complexity of time to the O (LOGN)

Computes X's M-Power (Recursive implementation)
//Time complexity O (logn)
function Exprec (x, m) {
  if (m = = 0) {return
    1;
  }
  var y = Exprec (x, Math.floor (M/2));
  y = y * y;
  if (m% 2!= 0) {
    y = x * y
  } return
  y;
}

Of course, this is not just a recursive credit, the improvement of its efficiency is mainly dependent on a mathematical common sense: x^m = [x^ (M/2)]^2, on this issue, there is a unique way of thinking is not recursive solution, cleverly using the characteristics of the binary

Converts a 10 number into a 2
-function toBin (dec) {
  var bits = [];
  var dividend = Dec;
  var remainder = 0;
  while (Dividend >= 2) {
    remainder = dividend% 2;
    Bits.push (remainder);
    Dividend = (dividend-remainder)/2;
  }
  Bits.push (dividend);
  Bits.reverse ();
  Return Bits.join ("");
}
To compute the M-power (non-recursive implementation) of X (not recursively)
//Very unique solution
function exp (x, m) {
  var y = 1;
  var bin = toBin (M). Split (");
  First converts m into a 2-in form for
  (var j = 0; J < Bin.length; J + +) {
    y = y * 2;
    If the first J bit of 2 is 1, then *x
    if (bin[j] = = "1") {
      y = x * y}} return
  y;
}
println (Exprec (2, 5));
PRINTLN (exp (2, 5));

Let's take a look at the classic polynomial evaluation problem:

Given a string of real an,an-1,...,a1,a0 and a real x, the value of the polynomial pn (x) is computed

The famous Horner formula:

How it has been calculated:

Clearly there are:

This only needs n times multiplication +n second addition

Polynomial evaluation
//n multiplication +n Second addition to fix, great improvement!
function Horner (A, x) {
  var n = a.length-1
  var p = a[n];
  for (var j = 0; J < N; j +) {
    p = x * p + a[n-j-1];
  }
  return p;
}
Calculated: Y (2) = 3x^3 + 2x^2 + x-1;
var A = [-1, 1, 2, 3];
var y = Horner (A, 2);
alert (y);//33

Most questions :

An array of n of elements that you want to quickly find that is greater than the number of occurrences of the >N/2 element (which is also called a majority element). It is usually used in the ballot system to quickly determine whether a candidate has more than half the votes. The optimal algorithm is as follows:

Find out most element
function candidate (A, m) {
  var count = 1, c = a[m], n = a.length-1, in array A "may exist";
  while (M < n && Count > 0) {
    m++;
    if (a[m] = = c) {
      count++
    }
    else {
      count--;
    }
  }
  if (M = = N) {return
    C;
  }
  else {return
    candidate (A, M + 1);
  }
}
Find most elements
//Time complexity O (n)
function majority (a) {
  var c = candidate (A, 0);
  var count = 0;
  Identified C, which may be most elements, may not be,
  //Must be counted again to ensure that the result is correct for
  (var i = 0; i < a.length i++) {
    if (a[i) = = c) {
      count+ +;
    }
  }
  If more than half, it is determined to be most elements
  if (Count > Math.floor (A.LENGTH/2)) {return
    C;
  }
  return null;
}
var m = majority ([3, 2, 3, 3, 4, 3]);
Alert (m);

The above algorithm is based on the conclusion that after removing two different elements in the original sequence, most of the elements in the original sequence are still most elements in the new sequence .

Proved as follows:

If the number of elements in the original sequence is n, most of the elements appear as x, then x/n > 1/2
Once you have removed two different elements,
A if the removed element does not include most elements, then the number of original most elements/new sequence elements in the new sequence = x/(n-2), because x/n > 1/2, so x/(n-2) also necessarily >1/2
b if the removed element contains most elements, the number of original most elements/new sequence elements = (x-1)/(N-2) in the new sequence, because x/n > 1/2 = "X>N/2" (x-1)/(N-2),
Have (x-1)/(N-2) > (N/2-1)/(N-2) = 2 (n-2)/(n-2) = 1/2

Next question: full arrangement

function swap (A, I, j) {
  var t = a[i];
  A[i] = a[j];
  A[J] = t;
}
function println (msg) {
  document.write (msg + "<br/>");
}
Full permutation algorithm
function perm (P, m) {
  var n = p.length-1;
  if (M = = N) {
    //complete a new arrangement, the output
    println (P);
    return;
  }
  for (var j = m; j <= N; j +) {
    //swap the starting element with each subsequent element for
    swap (P, J, M);
    The first m elements are already lined up on the basis of
    //plus an element for the new arrangement of
    Perm (P, M + 1);
    Swapping J and M back, resuming the "scene" before recursive calls,//
    Otherwise, the
    duplicate
    swap (P, J, M) could be generated if swap
was destroyed before recursive invocation,//caused by the subsequent generation of sort;
Perm ([1, 2, 3], 0);
1,2,3
//1,3,2
//2,1,3
//2,3,1
//3,2,1
//3,1,2

divided by the rule of law :

Important: When you divide the problem into two sub questions, try to make the child problems roughly equal in size. In this way to the greatest degree of embodiment in split, the scale of the problem by logarithmic binary to narrow the advantages.

Print output (Debug) function println (msg) {document.write (msg + "<br/>"); Element Exchange (auxiliary function) function swap (A, I, j) in the i,j position in an array
  {var t = A[i];
  A[i] = A[j];
A[J] = t;  //Looking for the maximum and minimum value (divide-and-conquer method) in array A function Findminmaxdiv (A, low, high) {//Minimum scale sub problem solution if (high-low = = 1) {if (A[low) <
    A[high]) {return [A[low], A[high]];
    else {return [A[high], A[low]];
  } var mid = Math.floor ((low + high)/2);
  To find the solution of a child problem in the first half of the element var r1 = Findminmaxdiv (A, Low, mid);
  Finding the solution of a child problem in the latter half of the element var r2 = Findminmaxdiv (A, mid + 1, high); Combine the two-part solution with var x = r1[0] > r2[0]?
  R2[0]: r1[0]; var y = r1[1] > r2[1]?
  R1[1]: r2[1];
return [x, y];
var r = Findminmaxdiv ([1, 2, 3, 4, 5, 6, 7, 8], 0, 7); println (R); 1,8//Two-point search (divide-and-conquer)/input: A for an array that has been sorted in a non descending order//x the value to search for//low,high the start, Stop index Range//Return of the search: If found, returns the subscript, otherwise returns-1 function Binarysearchdiv (a
  , x, Low, high} {if (Low > High) {return-1;
  var mid = Math.floor ((low + high)/2);
if (x = = A[mid]) {return mid;  else if (x < A[mid]) {return Binarysearchdiv (A, X, Low, mid-1);
  else {return Binarysearchdiv (A, X, mid + 1, high);
} var f = Binarysearchdiv ([1, 2, 3, 4, 5, 6, 7], 4, 0, 6); println (f);  3//The array A, bounded by the low position element, is divided into the front and back two//n for the upper bound function of the index range to be processed split (A, Low, N) {if (n >= a.length-1) {n = a.length-
  1;
  var i = low;
  var x = A[low]; Two pointers "Follow" one after the other,//the first pointer found that there is element score boundary element Hour, switch to the first half///behind the pointer again followed, "Fres" all the way for (var j = low + 1; J <= N; j + +) {if a[
      J] <= x) {i++;
      if (i!= j) {Swap (A, I, J);
  After the above toss, except for the low element, the other elements are in place//finally need to exchange the lower with the last element with a smaller lower position,///so that it can be placed in the watershed position swap (A, low, i);
return [A, I];
} var A = [5, 1, 2, 6, 3];
var B = Split (A, 0, a.length-1); println (B[0]);
  3,1,2,5,6//Quick Sort function quickSort (A, Low, High) {var w = high;
    if (Low < high) {var t = Split (A, Low, w);//Divide the thought, first divides into two half w = t[1];
    In the first half solves QuickSort (A, Low, w-1); In the latter half to solve quickSort (A, W + 1, high);
} var A = [5, 6, 4, 7, 3];
QuickSort (A, 0, a.length-1); println (A);

 3,4,5,6,7

the thought application of the split algorithm :

Set A[1..N] is an integer set, which gives an algorithm to rearrange the elements of an array, so that all negative integers are placed to the left of all nonnegative integers, and your algorithm should run at the time of Theta (n)

function Sort1 (A) {
  var i = 0, j = a.length-1;
  while (I < j) {
    if (A[i] >= 0 && a[j] >= 0) {
      j--;
    }
    else if (A[i] < 0 && A[j] < 0) {
      i++
    }
    else if (A[i] > 0 && a[j] < 0) {
      swap (A, I, j);
      i++;
      j--;
    }
    else {
      i++;
      j--
}
}} function Sort2 (A) {
  if (a.length <= 1) {return;}
  var i = 0;
  for (var j = i + 1; j < A.length J + +) {
    if (A[j] < 0 && A[i] >= 0) {
      swap (A, I, j);
      i++
}
}} var a = [1,-2, 3, -4, 5,-6, 0];
Sort1 (a);
println (a);//-6,-2,-4,3,5,1,0
var b = [1,-2, 3, -4, 5,-6, 0];
Sort2 (b);
println (b);//-2,-4,-6,1,5,3,0

I hope this article will help you with JavaScript programming.

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.