You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

快速排序元素交换次数统计异常问题求助

问题原因分析
  1. 错误的计数累加逻辑:quickSort函数里的count += count;完全错误,初始传入count=0时执行后仍为0,后续递归还会把计数错误翻倍,直接导致统计失效。
  2. 递归返回值未处理:递归调用quickSort时,没有接收子递归返回的更新后计数,上层函数无法获取下层的交换次数统计结果,最终返回的还是初始传入的0。
修复后的代码
var items = ["bcd", "abc", "dft", "def", "jhg"];
function swap(items, leftIndex, rightIndex) {
  var temp = items[leftIndex];
  items[leftIndex] = items[rightIndex];
  items[rightIndex] = temp;
}
function partition(items, left, right, count) {
  var pivot = items[Math.floor((right + left) / 2)],
    i = left,
    j = right;
  while (i <= j) {
    while (items[i] < pivot) {
      i++;
    }
    while (items[j] > pivot) {
      j--;
    }
    if (i <= j) {
      count++;
      swap(items, i, j);
      i++;
      j--;
    }
  }
  return { i, count };
}

function quickSort(items, left, right, count) {
  if (items.length <= 1) {
    return { items, count };
  }
  const partitionResult = partition(items, left, right, count);
  let totalCount = partitionResult.count;
  
  if (left < partitionResult.i - 1) {
    const leftSortResult = quickSort(items, left, partitionResult.i - 1, totalCount);
    totalCount = leftSortResult.count;
  }
  if (partitionResult.i < right) {
    const rightSortResult = quickSort(items, partitionResult.i, right, totalCount);
    totalCount = rightSortResult.count;
  }
  
  return { items, count: totalCount };
}

var sortedArray = quickSort(items, 0, items.length - 1, 0);
console.log("排序后数组: " + sortedArray.items);
console.log("总交换次数: " + sortedArray.count);
修复说明
  • 删除了quickSort中错误的count += count;语句,恢复正常的计数累加逻辑。
  • 递归调用时接收子函数返回的结果,更新当前总交换次数,确保下层统计结果能向上传递汇总。
  • 补充了数组长度小于等于1时的直接返回逻辑,避免无效递归。

内容的提问来源于stack exchange,提问作者Mohsen Rj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:31:15