【JavaScript算法】javascript常用算法

1、冒泡排序


function swap(arr, index1, index2) {
  var temp = arr[index1];
  arr[index1] = arr[index2];
  arr[index2] = temp;
}

function sortPop(inArray) {
  var len = inArray.length-1;
  for( var i = len; i >0; i-- ) {
    for(var j = 0; j <= i; j++ ) {

      if ( inArray[j] < inArray[j+1]) {
        swap(inArray, j, j+1);
      }
    }
  }
  return inArray;
}


2、选择排序


function sortSelect(inArray) {

    for( var i = 0; i < inArray.length-2; i++) {
      for(var j = i+1; j < inArray.length-1; j++ ) {
          if ( inArray[i] > inArray[j] ) {
            swap(inArray, i, j);
          }
      }
    }
  return inArray;
}


3、插入排序


function sortInsert(inArray) {

  var inner,temp;

  for( var outer = 1; outer < inArray.length-1; outer++) {

    temp = inArray[outer];

    inner = outer;

    while( inner > 0 && temp < inArray[inner-1]) {
      inArray[inner] = inArray[inner-1];
      inner--;
    }
    inArray[inner] = temp;

  }

  return inArray;
}


4、去除数组中重复的数据


function delRepeat(inArray) {
  var retArray = [];

  for( var i = 0, len = inArray.length; i < len; i++) {

    for (var j = i + 1; j < len; j++ ) {
      if ( inArray[i] == inArray[j] || typeof inArray[i] == 'undefined' ) {
        break;
      }
    }

    if ( j == len ) {
        retArray.push(inArray[i]);
    }

  }
  return retArray;
}





你可能感兴趣的:(【JavaScript算法】javascript常用算法)