首页 > Web开发 > 详细

js 统计逆序对的个数

时间:2020-04-27 17:28:14      阅读:56      评论:0      收藏:0      [点我收藏+]

1.分治思想,归并排序思想

// 过程:先把数组分割成子数组,先统计出子数组内部的逆序对的数目,然后再统计出两个相邻子数组之间的逆序对的数目。在统计逆序对的过程中,还需要对数组进行排序。如果对排序算法很熟悉,我们不难发现这个过程实际上就是归并排序
function InversePairs(data = []) {
  // write code here
  let len = data.length
  if (len === 0) return 0
  const copy = data.concat([])
  let count = InversePairsHelp(data, copy, 0, len - 1)
  return count
  function InversePairsHelp(data, copy, start, end) {
    if (start === end) {
      copy[start] = data[start]
      return 0
    }
    let mid = Math.floor((end - start) / 2)
    let left = InversePairsHelp(copy, data, start, start + mid)
    let right = InversePairsHelp(copy, data, start + mid + 1, end)
    let i = start + mid
    let j = end
    let count = 0
    let indexCopy = end
    while (i >= start && j >= start + mid + 1) {
      if (data[i] > data[j]) {
        copy[indexCopy--] = data[i--]
        count = count + j - start - mid
      } else {
        copy[indexCopy--] = data[j--]
      }
    }
    for (; i >= start; i--)
      copy[indexCopy--] = data[i]
    for (; j >= start + mid + 1; j--)
      copy[indexCopy--] = data[j]
    return left + right + count
  }
}

 

 

js 统计逆序对的个数

原文:https://www.cnblogs.com/ajaxkong/p/12787917.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!