JS implementation of front-end common algorithm

Source: Internet
Author: User

Algorithm is the soul of the program, a good front-end engineer to the algorithm is also to understand.

Sorting algorithms

1. Bubble sort

// Bubble Sort function Bubblesort (arr) {    var i = j = 0;      for (i=1;i<arr.length;i++) {        for (j=0;j<=arr.length-i;j++) {            var temp = 0;             if (arr[j]>arr[j+1]) {                = arr[j];                 = Arr[j+1];                Arr[j+1] = temp;     }}}}

2. Quick Sort

//Quick SortfunctionQuickSort (arr,l,r) {if(L <R) {        vari = l, j = r, x =Arr[i];  while(i<j) {             while(I<j && arr[j]>x) J--; if(i<j)//here with i++, is replaced by the inevitable than X small, after the assignment directly let I self-added, do not compare, can improve efficiencyarr[i++] =Arr[j];  while(I<j && arr[i]<x) I++; if(i<j)//here with j--, is replaced by the inevitable than X, the value of the direct let J self-reduction, no comparison, can improve efficiencyarr[j--] =Arr[i]; } Arr[i]=x; QuickSort (arr, L, I-1); QuickSort (arr, I+1, R); }}

3. Two-Way merge

Combining two ordered sequences of values into one ordered sequence of values, then called a two-way merge sort

functionmerge (left, right) {varresult =[], IL= 0, IR= 0;  while(Il < left.length && IR <right.length) {if(Left[il] <Right[ir]) {Result.push (Left[il++]); } Else{Result.push (Right[ir++]); }    }     while(Left[il]) {Result.push (Left[il++]); }     while(Right[ir]) {Result.push (Right[ir++]); }    returnresult;}

String manipulation

1. Judging a palindrome string

functionpalindrome (str) {//\w matches any non-word character. Equivalent to "[^a-za-z0-9_]".     varRe =/[\w_]/G; //turn the string into lowercase characters and kill the character except for the alpha-numeric    varLowregstr = Str.tolowercase (). replace (Re, '); //if the length of the string lowregstr is 0 o'clock, the string is Palindrome    if(lowregstr.length===0)        return true; //if the first and last characters of the string are not the same, the string is not a palindrome    if(lowregstr[0]!=lowregstr[lowregstr.length-1])        return false; //Recursive    returnPalindrome (Lowregstr.slice (1,lowregstr.length-1));}

2. Flipping a string

Idea 1: Backward traversal of strings

function reversestring (str) {    var tmp = ';      for (var i=str.length-1;i>=0;i--)         + = Str[i]    ; return tmp}

Idea 2: Converting to an array operation

function reverseString2 (str) {    var arr = Str.split ("");     var i = 0,j = Arr.length-1;      while (i<j) {        = arr[i];         = Arr[j];         = tmp;        I+ +;        J--;    }     return arr.join ("");}

3. Generate a random string of the specified length

with Blur and other effects can generate verification code

function randomstring (n) {    var str = ' abcdefghijklmnopqrstuvwxyz0123456789 ';     var tmp = ';      for (var i=0;i<n;i++)         + = Str.charat (Math.Round (Math.random () *str.length))    ; return tmp;}

4. Count the most frequently-counted letters in a string

Take advantage of the uniqueness of key in object, use key to filter, and then count

functionFindmaxduplicatechar (str) {if(Str.length = = 1) {        returnstr; }    varCharobj = {};  for(vari = 0; i < str.length; i++) {        if(!Charobj[str.charat (i)]) {Charobj[str.charat (i)]= 1; } Else{Charobj[str.charat (i)]+ = 1; }    }    varMaxchar = ' ', MaxValue= 1;  for(varKinchcharobj) {        if(Charobj[k] >=maxValue) {Maxchar=K; MaxValue=Charobj[k]; }    }    returnMaxchar + ': ' +MaxValue;}

Array manipulation

1. Array de-weight

Use key in object to filter by using the key's uniqueness

function Unique (arr) {    var obj = {}    var data = []    for ( var inch arr) {        if(!  Obj[arr[i]]) {            true;            Data.push (Arr[i]);        }    }     return data;}

2. Maximum difference in number array

function Getmaxprofit (arr) {    var min = arr[0], max = Arr[0];      for (var i=0;i<arr.length;i++) {        if(arr[i]<min)            = Arr[i];         if(arr[i]>max)            = arr[i];    }     return max- min;}

Other common algorithms

1. Factorial

//1. Non-recursive implementationsfunctionfactorialize (num) {varresult = 1; if(Num < 0)return-1; if(num = = 0 | | num = = 1)return1;  while(num>1) Result*= num--; returnresult;}//2. Recursive implementationsfunctionfactorialize (num) {varresult = 1; if(Num < 0)return-1; if(num = = 0 | | num = = 1)return1; if(Num > 1){        returnNum*factorialize (num-1); }}

2. Generating Fibonacci sequences

Fibonacci retracement: Also known as the Golden section of the series, it is worth a series: 0, 1, 2, 3, 5, 8, 13, 21, 34 ...., mathematically, the Fibonacci sequence mainly investigates recursive invocation.

2.1 Forced recursive implementation

functionGETFIB (n) {if(n = = 0)        return0; if(n = = 1)        return1; if(N > 1){        returnGETFIB (n-1) + GETFIB (n-2); }}functionFibo (len) {varFibo = [];  for(vari=0;i<len;i++) Fibo.push (Getfib (i)); returnFibo;}

2.2 Simple non-recursive implementation

function Getfibonacci (n) {    var fibarr = [];     var i = 0;      while (I < N) {        if(i <= 1) {            fibarr.push (i);         Else {            -1] + fibarr[i-2])        }        I++    ;    } return Fibarr;}

3. Two points Search

Binary search: is a more frequent algorithm used in an ordered array, the advantages are less than the number of comparisons, the search speed, the average performance is good, the disadvantage is that the unknown origin table is required to be ordered, and insert delete difficult

3.1 Non-recursive implementations

functionBinary_search (arr, key) {varLow = 0, High= Arr.length-1;  while(Low <=High ) {        varMid = parseint ((high + low)/2); if(Key = =Arr[mid]) {            returnmid; }Else if(Key >Arr[mid]) { Low= Mid + 1; }Else if(Key <Arr[mid]) { High= Mid-1; }    }    return-1;};

3.2 Recursive implementations

functionBINARY_SEARCH2 (arr, low, high, key) {if(Low >High )return-1; varMid = parseint ((low + high)/2);if(Key = =Arr[mid])returnmid; Else if(Key >Arr[mid])returnBINARY_SEARCH2 (arr, mid+1, high, key); Else if(Key <Arr[mid])returnBINARY_SEARCH2 (arr, Low, mid-1, key);}

  

JS implementation of front-end common algorithm

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.