---
title: "awk版堆排序 heapsort"
author: "polyahu"
date: "2013-10-29T10:56:04Z"
tags: []
categories: ["编程语言"]
slug: "awk-heapsort"
draft: false
lastmod: "2013-10-29T14:29:54Z"
id: 1965966
url: "https://polyahu.iteye.com/blog/1965966"
---

The AWK Programming Language书里
7.1节的heapsort段落

```Bash

#/bin/bash
echo | awk '
{ A[nr] = $0 }
END { hsort(A, NR)
      for (i = 1; i <= NR; i++)
          { print A[i] }
    }

function hsort(A, n, i) {
    for (i = int(n/2); i >= 1; i--)
         { heapify(A, i, n) }
    for (i = n; i > 1; i--) {
         { swap(A, 1, i) }
         { heapify(A, 1, i-1) }
    }
}
function heapify(A, left, right, p, c) {
    for (p = left; (c = 2*p) <= right; p = c) {
        if (c < right && A[c+1] > A[c])
            { c++ }
        if (A[p] < A[c])
            { swap(A, c, p) }
    }
}
function swap(A, i, j, t) {
    t = A[i]; A[i] = A[j]; A[j] = t
}' <<EOF
76
12
5
96
30
EOF

```