diveDylan / blog

My blog, detail is in the issues list
2 stars 0 forks source link

前端常用算法类 #23

Open diveDylan opened 4 years ago

diveDylan commented 4 years ago

本issuse用于手写一些前端常用算法

diveDylan commented 4 years ago

二分法

function dicphoni(arr, data){
       let min = 0
       let max = arr.length - 1
       while(min <=max) {
         const mean  = parseInt((min + max) / 2)
         if (data > mean) {
            min = mean + 1
         }
         if (data < mean) {
             max  = mean -1
         }
         if (data === mean) {
            return data
        }
     }
     return -1
}
diveDylan commented 4 years ago

lcs长队列中查找有序子序列

const lcs = (list, longList) => {
       const len = list.length
       let index= 0
       let hasList = 1
       for( var i = 0; i < len; i ++) {
             const a = longList.indexOf(list[i], index)
            if (a === -1) {
                result = 0
                 break;  
            } else {
                index= a
             }
    }
   return result

}
diveDylan commented 4 years ago

冒泡排序

const bubble = list => {
      const len = list.length
      for(var i =0; i < len; i ++) {
        for(var j = 0; j < len -i; j ++) {
          if (list[j] > list[j +1]) {
             [list[j + 1], list[j]] =[list[j], list[j +1]]
         }
       }
    }
      return list
}
diveDylan commented 4 years ago

块排

// TODO
// 网上看了一个三路快排的思想
function quickSort(list) {
const len = list.length
 if (len === 0) return []
 const left = []
const right = []
const center = []
 const base = list[0]

  for(let i = 0 ; i < len; i ++) {
       if ( i < base) {
        left.push(i)
    } else if( i > base) {
              right.push(i)
       }else {
             center.push(i)
     }
}
return [...quickSort(left), ...center, ...quickSort(right)]

}