---
title: "JS 堆排序"
author: "onestopweb"
date: "2018-07-18T16:06:36Z"
tags: ["堆排序", "排序"]
categories: ["Web前端"]
slug: "js"
draft: false
lastmod: "2018-07-18T16:06:36Z"
id: 2427091
url: "https://onestopweb.iteye.com/blog/2427091"
---

```
function heapSort(arr) {
  var len = arr.length;
  function swap(arr, rootIndex, maxIndex) {
      var temp = arr[rootIndex];
      arr[rootIndex] = arr[maxIndex];
      arr[maxIndex] = temp;
  }
  function diff(arr, index) {
      var leftIndex = 2 * index + 1;
      var rightIndex = 2 * index + 2;
      var maxIndex = index;

      if (leftIndex < len && arr[leftIndex] > arr[maxIndex]) {
          maxIndex = leftIndex
      }
      if (rightIndex < len && arr[rightIndex] > arr[maxIndex]) {
          maxIndex = rightIndex
      }
      if (maxIndex !== index) {
          swap(arr, index, maxIndex);
          diff(arr, maxIndex);
      }
  }
  for (var i = Math.floor(len / 2); i >= 0; i--) {
      diff(arr, i)
  }
  for (var j = len - 1; j >= 0; j--) {
      len--;
      swap(arr, 0, j);
      diff(arr, 0);
  }
  return arr;
}

console.log(heapSort([-4, 8, 6, 3, 0, 2, 5, -1, 4, 1]));
```

 

效果图：

![](http://dl2.iteye.com/upload/attachment/0130/2941/b8b16bcf-88cb-3f83-817c-f39f88504540.png)  
 

感谢大树的帮助。