The following is a simple list of some common JavaScript algorithms, need friends can do a reference. Of course, these algorithms apply not only to JavaScript, but also to other languages.
A. Linear search:
Simpler, entry-level algorithms
A is an array, x is the value to search for
function Linearsearch (A, x) {for
(var index = 0; index < a.length; index++) {
if (a[index) = = x) {return
index;
}}
return-1;
}
Two. Two point search:
Also known as binary lookup, it is suitable for the linear structure which has been sorted well.
A is an array that has been sorted in ascending order, X is the
subscript
function BinarySearch (A, x) {var low = 0) for the element to be queried//return the target element
, high = 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;
}
Three. Bubble sort:
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;}}}
Four. Insert Sort:
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,
//and the target element is inserted into the pit
. function Insertsort (A) {for
(var index= 1; index< a.length; index++) {
var x = A[index];
for (var j = index-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;
}
Five. String inversion:
string reversal (e.g., ABC-> CBA)
function Inverse (s) {
var arr = s.split (');
var index= 0, j = arr.length-1;
while (index< j) {
var t = Arr[index];
Arr[index] = arr[j];
ARR[J] = t;
index++;
j--;
}
Return Arr.join (");
}
The above content gives everybody simple introduction Javascrip common algorithm Summary, hoped this article can bring the help to everybody.