js实现基础算法以及堆栈实现

2019-04-07  本文已影响0人  夜雨惊人
算法复杂度.png

冒泡排序

function sort(element){
        for(var i = 0;i<element.length-1;i++) {
            console.log("i="+element[i])
            for(var j = 0;j<element.length-i-1;j++){
                console.log("j="+element[j]);
                console.log("j+1="+element[j+1]);
                if(element[j]>element[j+1]){
                    //把大的数字放到后面
                    var swap = element[j];
                    element[j] = element[j+1];
                    element[j+1] = swap;
                }
            }
            console.log(element);
        }
    }
    var element = [3,5,1,2,7,8,4,5,3,4];
    //console.log("before:"+element);[3,5,1,2,7,8,4,5,3,4];
    sort(element);
    //console.log("after:"+element);[1, 2, 3, 3, 4, 4, 5, 5, 7, 8]

快速排序

var quickSort = function(arr) {
    if (arr.length <= 1) { return arr; }
    var pivotIndex = Math.floor(arr.length / 2);   //基准位置(理论上可任意选取)
    var pivot = arr.splice(pivotIndex, 1)[0];  //基准数
    var left = [];
    var right = [];
    for (var i = 0; i < arr.length; i++){
        if (arr[i] < pivot) {
            left.push(arr[i]);
        } else {
            right.push(arr[i]);
        }
    }
    return quickSort(left).concat([pivot], quickSort(right));  //链接左数组、基准数构成的数组、右数组
};

选择排序:

function selectionSort(arr) {
    var len = arr.length;
    var minIndex, temp;
    for (var i = 0; i < len - 1; i++) {
        minIndex = i;
        for (var j = i + 1; j < len; j++) {
            if (arr[j] < arr[minIndex]) {     // 寻找最小的数
                minIndex = j;                 // 将最小数的索引保存
            }
        }
        temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }
    return arr;
}

希尔排序:

function shellSort(arr) {
    var len = arr.length,
        temp,
        gap = 1;
    while(gap < len/3) {          //动态定义间隔序列
        gap = gap*3+1;
    }
    for (gap; gap > 0; gap = Math.floor(gap/3)) {
        for (var i = gap; i < len; i++) {
            temp = arr[i];
            for (var j = i-gap; j >= 0 && arr[j] > temp; j -= gap) {
                arr[j+gap] = arr[j];
            }
            arr[j+gap] = temp;
        }
    }
    return arr;
}

归并排序

function mergeSort(arr) {
  let len = arr.length;
  if(len > 1) {
    let index = Math.floor(len / 2);
    left = arr.slice(0,index); //得到下标从0~index-1的数组
    right = arr.slice(index);  //得到下标从index开始到末尾的数组
    return merge(mergeSort(left) , mergeSort(right));  里面采用递归
  }else {
    return arr;
  }
}
//该函数与快排类似,但是仔细发现,每次left或者right都是要shift掉第一个元素,表示left或者right是会变化的,最后arr.concat,因为不知道left或者right其中一个哪个剩下元素,所以要将剩下的元素给加上
function merge(left , right) {   
  let arr = [];
  while(left.length && right.length) {
    if(left[0] < right[0]) {
      arr.push(left.shift());
    }else {
      arr.push(right.shift())
    }
  }
  return arr.concat(left , right);
}

数组常用方式

栈:

    function divideBy2(decNumber){
      var decStack = new Stack();
      var rem;
      var decString = '';
      while(decNumber > 0){
        rem = decNumber%2;
        decStack.push(rem);
        decNumber = Math.floor(decNumber/2);
      }
      while(!decStack.isEmpty()){
        decString += decStack.pop().toString();
      }
      return decString;
    }
    console.log(divideBy2(10));//1010

队列

链表

//寄生组合式继承实现,详见javascript高级程序设计第七章
   function inheritPrototype(subType, superType) {
       function object(o) {
           function F() {}
           F.prototype = o;
           return new F();
       }
       var prototype = object(superType.prototype);
       prototype.constructor = subType;
       subType.prototype = prototype;
   }
   function DoublyLinkedList() {
       function Node(element) {
           this.element = element;
           this.next = null;
           this.prev = null;
       }
       this.tail = null;
       LinkedList.call(this);
       //与LinkedList不同的方法自己实现。
       this.insert = function(position, element) {
           if (position > -1 && position <= this.length) {
               var node = new Node(element);
               var current = this.head;
               var previous;
               var index = 0;
               if (position === 0) {
                   if (!this.head) {
                       this.head = node;
                       this.tail = node;
                   } else {
                       node.next = current;
                       current.prev = node;
                       this.head = node;
                   }
               } else if (position == this.length) {
                   current = this.tail;
                   current.next = node;
                   node.prev = current;
                   this.tail = node;
               } else {
                   while (index++ < position) {
                       previous = current;
                       current = current.next;
                   }
                   previous.next = node;
                   node.next = current;
                   current.prev = node;
                   node.prev = previous;
               }
               this.length++;
               return true;
           } else {
               return false;
           }
       };
       this.append = function(element) {
           var node = new Node(element);
           var current;
           if (this.head === null) {
               this.head = node;
               this.tail = node;
           } else {
               current = this.head;
               while (current.next !== null) {
                   current = current.next;
               }
               current.next = node;
               node.prev = current;
               this.tail = node;
           }
           this.length++;
       };
       this.removeAt = function(position) {
           if (position > -1 && position < this.length) {
               var current = this.head;
               var previous;
               var index = 0;
               if (position === 0) {
                   this.head = current.next;
                   if (this.length === 1) {
                       this.tail = null;
                   } else {
                       this.head.prev = null;
                   }
               } else if (position === (this.length - 1)) {
                   current = this.tail;
                   this.tail = current.prev;
                   this.tail.next = null;
               } else {
                   while (index++ < position) {
                       previous = current;
                       current = current.next;
                   }
                   previous.next = current.next;
                   current.next.prev = previous;
               }
               this.length--;
               return current.element;
           } else {
               return false;
           }
       };
   }
   inheritPrototype(DoublyLinkedList, LinkedList);

//    test
 var doublyList = new DoublyLinkedList();
    console.log(doublyList.isEmpty()); //true;
    doublyList.append('a');
    doublyList.append('c')
    doublyList.insert(1, 'b');
    console.log(doublyList.toString()); //'abc'
    console.log(doublyList.indexOf('c')); //2
    console.log(doublyList.size()); //3
    console.log(doublyList.removeAt(2)); //c
    console.log(doublyList.toString()); //'ab'
上一篇 下一篇

猜你喜欢

热点阅读