堆排序:
堆排序分为三个步骤:
1.HEAPIFY(堆化,将指定的数据区调整成一个堆)
2.BUILD_HEAP(建堆,将整块数据建成一个堆)
3.HEAPSORT(排序,调整堆)
伪码:
Heapify (A, i)
- l
← left [i]
- r
← right [i]
- if l ≤ heap-size [A] and
A[l] > A[i]
- then largest
←
l
- else largest
←
i
- if r ≤ heap-size [A] and
A[i] > A[largest]
- then largest
←
r
- if largest ≠ i
- then exchange A[i]
↔ A[largest]
- Heapify (A, largest)
BUILD_HEAP (A)
- heap-size (A)
← length [A]
- For i ←
floor(length[A]/2)
down to 1 do
- Heapify (A, i)
HEAPSORT (A)
- BUILD_HEAP (A)
- for i ←
length (A) down
to 2 do
exchange A[1] ↔
A[i]
heap-size [A]
← heap-size [A]
- 1
Heapify (A, 1)
- void heapSort(int numbers[], int array_size)
-
{
-
int i, temp;
-
-
for (i = (array_size / 2)-1; i >= 0; i--)
-
siftDown(numbers, i, array_size);
-
-
for (i = array_size-1; i >= 1; i--)
-
{
-
temp = numbers[0];
-
numbers[0] = numbers[i];
-
numbers[i] = temp;
-
siftDown(numbers, 0, i-1);
-
}
-
}
-
-
-
void siftDown(int numbers[], int root, int bottom)
-
{
-
int done, maxChild, temp;
-
-
done = 0;
-
while ((root*2 <= bottom) && (!done))
-
{
-
if (root*2 == bottom)
-
maxChild = root * 2;
-
else if (numbers[root * 2] > numbers[root * 2 + 1])
-
maxChild = root * 2;
-
else
-
maxChild = root * 2 + 1;
-
-
if (numbers[root] < numbers[maxChild])
-
{
-
temp = numbers[root];
-
numbers[root] = numbers[maxChild];
-
numbers[maxChild] = temp;
-
root = maxChild;
-
}
-
else
-
done = 1;
-
}
-
}
阅读(1044) | 评论(0) | 转发(0) |