涂鸦-草稿:堆排序(2)
昨天晚上做了个小根堆,从小到大排序。
刚刚吃完午饭,没事干,就做了个大根堆,从大到小排序,练习练习~
不要看昨天的,凭感觉来,直接coding。
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
void print_arr(int *arr, int size)
{
int i;
for (i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
void siftdown(int *arr, int nowPos, int maxPoss)
{
int left = nowPos * 2 + 1;
int right = nowPos * 2 + 2;
int maxPos = nowPos;
if (left <= maxPoss)
{
if (arr[left] > arr[maxPos])
maxPos = left;
if (right <= maxPoss && arr[right] > arr[maxPos])
maxPos = right;
if (maxPos != nowPos)
{
int tmp = arr[maxPos];
arr[maxPos] = arr[nowPos];
arr[nowPos] = tmp;
return siftdown(arr, maxPos, maxPoss);
}
}
}
void siftup(int *arr, int nowPos)
{
if (nowPos == 0)
return;
int fatherPos = (nowPos - 1) / 2;
if (arr[fatherPos] < arr[nowPos])
{
int tmp = arr[fatherPos];
arr[fatherPos] = arr[nowPos];
arr[nowPos] = tmp;
return siftup(arr, fatherPos);
}
}
void createHeap(int *arr, int size, int *p)
{
int i;
for (i = 0; i < size; i++)
{
p[i] = arr[i];
siftup(p, i);
}
}
void heapSort(int *arr, int size)
{
int *p = (int *)malloc(sizeof(int) * size);
memset(p, 0, sizeof(int) * size);
createHeap(arr, size, p);
printf("after createHeap:\n");
print_arr(p, size);
int index = 0;
while (size)
{
arr[index] = p[0];
printf("max is %d\n", arr[index]);
p[0] = p[size-1];
index++;
size--;
printf("before siftdown:\n");
print_arr(p, size);
siftdown(p, 0, size - 1);
printf("after siftdown:\n");
print_arr(p, size);
}
free(p);
p = NULL;
}
int main()
{
int arr[14] = {1, 2, 5, 12, 7, 17, 25, 19, 36, 99, 22, 28, 46, 92};
printf("original data:\n");
print_arr(arr, 14);
heapSort(arr, 14);
printf("sorted data:\n");
print_arr(arr, 14);
return 0;
}
估计我这的这个代码有很多bug~呃呃,意思大概就是这样。
没事的时候敲点代码玩~
Happy Coding!