堆排序是基本却非常重要的排序算法之一,经常在面试中出现,相对来说也比较难些。现在我以C和Python给出自己的源码仅供参考。
另外,如果觉得我写的好,可以关注我的github帐号(https://github.com/chenqiangzhishen). 本文代码部分我也贴在了如下的目录中。
(https://github.com/chenqiangzhishen/Algorithms/blob/master/sorts/heapSort/heapSort.c)
(https://github.com/chenqiangzhishen/Algorithms/blob/master/sorts/heapSort/heapSort.py)
有了github,我会经常更新些新的,高效的,经典的算法和其他新的知识与大家分享,开源快乐~
注:我的代码不出意外,都可以直接运行,采用gcc/g++/gdb进行的开发与调试工具及vim开发工具。
因为比较喜欢在Linux下编程,不大喜欢用中文切来切去的进行描述,所以直接采用英文进行注释。
C语言版本如下:
#include <stdio.h>
void adjustHeap(int data[], int beg, int end)
{
if(data==NULL || beg>=end)
return;
int i=0;
int temp = data[beg];
for(i=2*beg+1; i<=end; i*=2)//note the index
{
if(i+1<=end && data[i]<data[i+1])//if right child bigger than left, then point to right child.
++i;
if(temp >= data[i])//if parent bigger than childen, keep bigger.
break;
data[beg] = data[i];//exchange value for child and parent.
beg = i;
}
data[beg] = temp;//insert the original parent data
}
void heapSort(int data[], int length)
{
if(data==NULL || length<=0)
return;
int i=0;
for(i=length/2-1; i>=0; --i)
{
adjustHeap(data, i, length-1);
}
for(i=length-1; i>0; --i)
{
data[i] ^= data[0];
data[0] ^= data[i];
data[i] ^= data[0];
adjustHeap(data, 0, i-1);
}
}
int main(void)
{
int i = 0;
int data[] = {1,7, 4};
int length = sizeof(data)/sizeof(data[0]);
printf("before sorting the data is :");
for(i=0; i<length; ++i)
{
printf("%d ", data[i]);
}
printf("
");
printf("after sorting the data is :");
heapSort(data, length);
for(i=0; i<length; ++i)
{
printf("%d ", data[i]);
}
printf("
");
return 0;
}
Python版本如下:
#!/usr/bin/python
def adjustHeap(dataList, beg, end):
if len(dataList)==0 or beg >end:
return
temp = dataList[beg]
i = 2*beg +1
while i<=end:
if i+1<=end and dataList[i]<dataList[i+1]:
i += 1 # note that there no ++i or i++ in the python
if(temp >= dataList[i]):
break
dataList[beg] = dataList[i]
beg = i
i = 2*beg +1
dataList[beg] = temp
def heapSort(dataList):
if len(dataList)==0:
return
for i in range(len(dataList)/2-1, -1, -1):
adjustHeap(dataList, i, len(dataList)-1)
for i in range(len(dataList)-1, 0, -1):
dataList[0], dataList[i] = dataList[i], dataList[0]
adjustHeap(dataList, 0, i-1)
def main():
data = [4, 1, 3, 6, 8, 9, 0, 2, 5, 7]
print "the original data is:"
print data
print "after sorting data is:"
heapSort(data)
print data
if __name__ == "__main__":
main()