JavaScript implementation of some common algorithms

Source: Internet
Author: User

In Web development, JavaScript and algorithms are also important. The following describes the implementation of some common algorithms in JavaScript, this includes binary classification, String Length determination, array deduplication, insertion sorting, selection sorting, Hill sorting, fast sorting, and Bubble sorting. It is only for the sake of practice, which does not guarantee the efficiency and appearance. There may be bugs, so please try again later.

Dichotomy:

function binary(items,value){ var startIndex=0,     stopIndex=items.length-1,     midlleIndex=(startIndex+stopIndex)>>>1;     while(items[middleIndex]!=value && startIndex<stopIndex){       if(items[middleIndex]>value){          stopIndex=middleIndex-1;       }else{          startIndex=middleIndex+1;       }       middleIndex=(startIndex+stopIndex)>>>1;     }     return items[middleIndex]!=value ? false:true;}

Random generation of hexadecimal color values:

function randomColor(){ var arrHex=["0","2","3","4","5","6","7","8","9","a","b","c","d"],     strHex="#",     index;     for(var i=0;i < 6; i++){      index=Math.round(Math.random()*15);      strHex+=arrHex[index];     } return strHex;}

A Method to Evaluate the length of a string:

function GetBytes(str){ var len=str.length,     bytes=len; for(var i=0;i < len;i++){   if(str.CharCodeAt>255){     bytes++;   } } return bytes;}

Js implements array deduplication:

Array.protype.delRepeat=function(){  var newArray=new Array();  var len=this.length;  for(var i=0;i < len;i++){     for(var j=i+1;j < len;j++)     {       if(this[i]==this[j])       {         ++i;         }     }    newArray.push(this[i]);  } return newArray;}

Insert sorting. The so-called insertion sorting means to regard the first element in the sequence as an ordered subsequence, and then compare and exchange the values without further comparison.

Function insertSort (arr) {var key; for (var j = 1; j <arr. length; j ++) {// sort the var I = j-1; key = arr [j]; while (I >=0 & arr [I]> key) {arr [I + 1] = arr [I]; I --;} arr [I + 1] = key;} return arr ;}

Select sort. In fact, the basic idea is to select the smallest or largest value from the array to be sorted, put it at the starting position, and then select the smallest or largest number behind the company number from the remaining array.

function selectionSort(data){var i, j, min, temp , count=data.length;for(i = 0; i < count - 1; i++) {   /* find the minimum */   min = i;      for (j = i+1; j < count; j++)    {    if (data[j] < data[min])            { min = j;}     }       /* swap data[i] and data[min] */      temp = data[i];     data[i] = data[min];    data[min] = temp;}return data;}

Hill sorting, also known as the descending incremental sorting algorithm. In fact, it is also a variant of insert sorting.

Function shellSort (array) {var stepArr = [1750,701,301,132, 57, 23, 10, 4, 1]; // reverse () on the Wiki, we can see that this optimal step size is small array var I = 0; var stepArrLength = stepArr. length; var len = array. length; var len2 = parseInt (len/2); for (; I <stepArrLength; I ++) {if (stepArr [I]> len2) {continue ;} stepSort (stepArr [I]);} // sort a step function stepSort (step) {// console. step used by log (step): var I = 0, j = 0, f, tem, key; var ste PLen = len % step> 0? ParseInt (len/step) + 1: len/step; for (; I <step; I ++) {// sequential loop column for (j = 1; /* j <stepLen & */step * j + I <len; j ++) {// cyclically loops each row of each column. tem = f = step * j + I; key = array [f]; while (tem-= step)> = 0) {// search for if (array [tem]> key in sequence) {array [tem + step] = array [tem];} else {break ;}} array [tem + step] = key ;}} return array ;}

Fast sorting. In fact, in the end, the quick sorting algorithm is an improvement of the Bubble sorting. It adopts the Division recursion idea in the algorithm theory. To be clear, its approach is: sort the records to be sorted into two parts. If the values of some of the records are smaller than those of the other parts, they can be sorted separately; the preceding two operations are performed recursively without segments to sort the record values.

function quickSort(arr,l,r){if(l < r){var mid=arr[parseInt((l+r)/2)],i=l-1,j=r+1;while(true){while(arr[++i] < mid);while(arr[--j]>mid);if(i>=j)break;var temp=arr[i];arr[i]=arr[j];arr[j]=temp;}quickSort(arr,l,i-1);quickSort(arr,j+1,r);}return arr;}

Bubble Method:

function bullSort(array){var temp;for(var i=0;i < array.length;i++){   for(var j=array.length-1;j > i;j--){     if(array[j] < array[j-1]){temp = array[j];array[j]=array[j-1];array[j-1]=temp;     }   } } return array;}

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.