1. 程式人生 > >排序算法之js實現回顧

排序算法之js實現回顧

快排 算法 bubble index length 完成 children log 數據

1. 時間復雜度就是while的次數,二分查找O(h)=O(log2n)

2. 節點的廣度優先遍歷

function traverse(root){
  const queue = [root];
  while(queue.length){
    const node = queue.shift();
    printInfo(node);
   
    if(!node.children.length){
      continue;
    }
    Array.from(node.children).forEach(x=>queue.push(x));
  }
}
function printInfo(node){ console.log(node.nodeName, node.className) } traverse(root)

3. DOM樹的深度優先遍歷

function printInfo(node, layer){
  var str = ‘‘
  for (let i = 1; i < layer; i++) {
    str += ‘ ‘
  }
 console.log(`${layer}:${str}${node.tagName}.${node.className}`);
}
function dfs = (rootNodes, rootLayer) => {
  const roots 
= Array.from(rootNodes) while (roots.length) { const root = roots.shift(); printInfo(root, rootLayer); if (root.children.length) { dfs(root.children, rootLayer + 1) } } } 

4. 冒泡排序(O(n^2))

它重復地走訪過要排序的數列,一次比較兩個元素,如果他們的順序錯誤就把他們交換過來。走訪數列的工作是重復地進行直到沒有再需要交換,也就是說該數列已經排序完成。

function bubbleSort(arr){
  const len = arr.length;
  for(let i = 0; i < len; i++){
    for(let j = 0; j < len - 1 - i; j++){
      if(arr[j] > arr[j + 1]){
        [arr[j], arr[j+1]] = [arr[j+1], arr[j]];
      }
    }
  }
  return arr;
}

5. 快排(O(nlogn))

通過一趟排序將要排序的數據分割成獨立的兩部分,其中一部分的所有數據都比另外一部分的所有數據都要小,然後再按此方法對這兩部分數據分別進行快速排序,整個排序過程可以遞歸進行,以此達到整個數據變成有序序列。

var quickSort = function(arr){
  if(arr.length <= 1) {return arr;}
  const midIndex = Math.floor(arr.length / 2);
  const mid = arr.splice(midIndex, 1)[0];
  const left = [], right = [];
  arr.forEach(function(item){
    if(item < mid){
      left.push(item);
    }else{
      right.push(item);
    }
  })
  return quickSort(left).concat([mid], quickSort(right));
}

 

排序算法之js實現回顧