JavaScript实现排序

之前去过一些公司做笔试题,排序算是比较基础的知识了,当时要求用JavaScript写出快速排序,当时不会就用Java语言写的。
****快速排序****

function quickSort(a){
      if(a.length<=1)//边界条件判断
            return a;
      var midLength = Math.floor(a.length/2);
      var midValue = a.splice(midLength,1);
      var left = [];
      var right = [];
      for(var i = 0; i<a.length; i++){
           if(a[i] < midValue){
                  left.push(a[i]);
           }else{
                  right.push(a[i]);
           }
      }
      return quickSort(left).concat(midValue,quickSort(right));
}
console.log(quickSort([1,3,5,2,4,7,9,6,8]));

****冒泡排序****

function bubbleSort(a) {
      var length = a.length;
      var sortArray;
      for(var i = 0; i<length-1; i++){
             for(var j = 0; j<length-1; j++){
                     if(a[j]>a[j+1]){
                           sortArray = a[j];
                           a[j] = a[j+1];
                           a[j+1] = sortArray;
                     }
             }
      }
      return a;
}
console.log(bubbleSort([1,3,5,2,4,7,9,6,8]));

****插入排序****

function insertSort(a) {
      var length = a.length;
      var sortArray;
      for(var i = 1; i < length; i++) {
             for(var j = 0; j < i; j++){
                  if(a[i] < a[j]){
                        sortArray = a[i];
                        a[i] = a[j];
                        a[j] = sortArray;
                  }
             }
      }
      return a;
}
console.log(insertSort([1,3,5,2,4,7,9,6,8]));

****选择排序****

function selectSort(a){
      for(var i = 0; i < a.length; i++){
              var min = a[i];
              var k = i;
              for(var j = i+1; j<a.length; j++){
                      if(min > a[j]){
                           min = a[j];
                           k = j;
                      }
              }
              a[k] = a[i];
              a[i] = min;    
      }
      return a;
}
console.log(selectSort([1,3,5,2,4,7,9,6,8]));
    原文作者:BrianAguilar
    原文地址: https://www.jianshu.com/p/6b62e68f58cd
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞