JS implementation of common algorithm in front-end

Source: Internet
Author: User

1. Bubble sort
function bubbleSort(arr){  var i = 0, 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]){ temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } return arr;}
2. Quick Sort
function quickSort(arr,l,r){  if(l < r){ var i = l, j = r, x = arr[i]; while(i<j){ while(i<j && arr[j]>x) j--; if(i<j) //这里用i++,被换过来的必然比x小,赋值后直接让i自加,不用再比较,可以提高效率 arr[i++] = arr[j]; while(i<j && arr[i]<x) i++; if(i<j) //这里用j--,被换过来的必然比x大,赋值后直接让j自减,不用再比较,可以提高效率 arr[j--] = arr[i]; } arr[i] = x; quickSort(arr, l, i-1); quickSort(arr, i+1, r); }}
3, two-way merger
function merge(left, right) {    var result = [], 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++]); } return result;}
String manipulation 1, judging palindrome string
functionPalindrome (STR) {\w matches any non-word character. Equivalent to "[^a-za-z0-9_]".var re =/[\w_]/g; //the string into lowercase characters and kills the character except the alpha-numeric var lowregstr = 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, then the string is not palindrome if (lowregstr[< Span class= "Hljs-number" >0]!=lowregstr[lowregstr.length-1]) return FALSE; //recursive return palindrome (Lowregstr.slice ( 1,lowregstr.length-1));       
2, flip the string idea one: Backward traversal string
function reverseString(str){  var tmp = ‘‘; for(var i=str.length-1; i>=0; i--) tmp += str[i]; return tmp}
Idea two: Convert to array operation
function reverseString(str){  var arr = str.split(""); var i = 0,j = arr.length-1; while(i<j){ tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; } return arr.join("");}
3. Generate random string of specified length
function randomString(n){  var str = ‘abcdefghijklmnopqrstuvwxyz0123456789‘; var tmp = ‘‘; for(var i=0; i<n; i++) { tmp += str.charAt(Math.round(Math.random()*str.length)); } return tmp;}
4. Maximum number of letters in the statistics string
functionFindmaxduplicatechar (STR) {if (str.length = =1) {return str;} var charobj = {}; for (var i = 0; i < str.length; i++ {if (!charobj[str.charat (i)]) {Charobj[str.charat (i)] = 1; Span class= "Hljs-keyword" >else {Charobj[str.charat (i)] + = 1;} var Maxchar =  ", MaxValue = 1; for (var k in charObj) {if (Charobj[k] >= maxValue) {Maxchar = k; maxValue = Charobj[k];}} return Maxchar +  ': ' + maxValue;}      
Array operation 1, array de-weight
function unique(arr){  var obj = {} var result = [] for(var i in arr){ if(!obj[arr[i]]){ obj[arr[i]] = true; result.push(arr[i]); } } return result;}
2, the maximum difference in the array
function getMaxProfit(arr){  var min = arr[0], max = arr[0]; for(var i = 0; i < arr.length; i++){ if(arr[i] < min) min = arr[i]; if(arr[i] > max) max = arr[i]; } return max - min;}
Other common algorithms 1, factorial non-recursive implementation
function factorialize(num) {  var result = 1; if(num < 0) return -1; if(num == 0 || num == 1) return 1; while(num>1) { result *= num--; } return result;}
Recursive implementation
function factorialize(num) {  var result = 1; if(num < 0) return -1; if(num == 0 || num == 1) return 1; if(num > 1) return num*factorialize(num-1);}
2, generate Fibonacci that cut the number of forced recursive implementation
functionGETFIB (N) { if (n = = 0) return 0; if (n = = 1) return 1; if (n > 1) return GETFIB (n-1) + GETFIB (n-2);} function Fibo (len) { var fibo = []; For (var i = 0; i < len; i++) {Fibo.push (Getfib (i));} return Fibo;}                  
Simple non-recursive implementation
function getFibonacci(n) {  var fibarr = []; var i = 0; while(i < n) { if(i <= 1) { fibarr.push(i); } else { fibarr.push(fibarr[i - 1] + fibarr[i - 2]) } i++; } return fibarr;}
3, two-part search for non-recursive implementation
function binary_search (arr, key) { var = 0, high = arr.length- 1; while (low <= high) { var mid = parseint (high + Low)/ 2); if (key = = Arr[mid]) { return mid;} Else if (key > Arr[mid]) {low = mid + 1;} Else if (Key < Arr[mid]) {high = mid -1;}} return -1;}                 
Recursive implementation
function binary_search2 (arr, Low, high, key) {if (Low > High)  return -1; var mid = parseint ((Low + high)/2) ; if (key = = Arr[mid]) {return mid;} else if (Key > Arr[mid]) { Return Binary_search2 (arr, Mid+1, high, key);} else if (Key < Arr[mid]) { Return BINARY_SEARCH2 (arr, Low, Mid-1, Key);}}       

JS implementation of common algorithms in front-end

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.