小顶堆排序:
#include <iostream>
using namespace std;
inline int left(int i)
{
return i<<1;
}
inline int right(int i)
{
return i<<1|1;
}
int heap_size;
int array_size;
void heap_mini(int *heap, int i)
{
int l = left(i);
int r = right(i);
int smallest;
if(l <= heap_size && heap[l] < heap[i])
smallest = l;
else smallest = i;
if(r <= heap_size && heap[r] < heap[smallest])
smallest = r;
if(smallest != i)
{
int t = heap[i];
heap[i] = heap[smallest];
heap[smallest] = t;
heap_mini(heap, smallest);
}
}
void build_heap(int *heap)
{
heap_size = array_size;
for(int i = array_size/2; i >= 1; i--)
heap_mini(heap, i);
}
void heap_sort(int *heap)
{
build_heap(heap);
for(int i = array_size; i >= 2; i--)
{
int t = heap[1];
heap[1] = heap[i];
heap[i] = t;
heap_size--;
heap_mini(heap, 1);
}
}
int main()
{
int n;
cout<<"please enter:"<<endl;
while(cin >> n)
{
array_size = n;
int heap[20] = { 0 }, i;
for(i = 1; i <= n; i++)
cin>>heap[i];
heap_sort(heap);
for(i = 1; i <= n; i++)
cout<<heap[i]<<" ";
cout<<endl;
cout<<"please enter:"<<endl;
}
return 0;
}
大顶堆排序:
//大顶堆
#include <iostream>
using namespace std;
int A_size;//数组大小
int heap_size;//堆的大小
//左孩子坐标
inline int left(int i)
{
return i<<1;
}
//右孩子坐标
inline int right(int i)
{
return i<<1|1;
}
//堆最大化
void max_heapify(int *A, int i)
{
int l = left(i);
int r = right(i);
int largest = 0;
if(l <= heap_size && A[l] > A[i])
largest = l;
else largest = i;
if(r <= heap_size && A[r] > A[largest])
largest = r;
if(largest != i)
{
int t = A[i];
A[i] = A[largest];
A[largest] = t;
max_heapify(A, largest);
}
}
//build heap
void build_heap(int *A)
{
heap_size = A_size;
for(int i = A_size/2; i >= 1; i--)
max_heapify(A, i);
}
//堆排序
void heap_sort(int *A)
{
build_heap(A);
for(int i = A_size; i >= 2; i--)
{
int t = A[1];
A[1] = A[i];
A[i] = t;
heap_size--;
max_heapify(A, 1);
}
}
int main()
{
int n;
cout<<"please enter n:"<<endl;
while(cin >> n)
{
A_size = n;
int A[100] = { 0 };
int i;
for(i = 1; i <= n; i++)
cin>>A[i];
heap_sort(A);
for(i = 1; i <= n; i++)
cout<<A[i]<<" ";
cout<<endl;
cout<<"please enter n:"<<endl;
}
return 0;
}