【算法学习】排序算法-堆排序
2014-11-27 20:22
211 查看
思想:
对全部元素n-1建立大顶堆后,将顶与最后一个元素交换;而后对n-2个元素建堆,将顶与倒数第二个元素交换;
直到最后两个元素建堆。
C代码
#include "stdio.h"void array_printf(int a[],int n);
void sort_heap(int a[],int n);
void build_heap(int a[],int e);
int main()
{
int i,a[] = {5,4,3,2,10,9,17,4,2,19,11};
int n = sizeof(a)/sizeof(int);
sort_heap(a,n);
array_printf(a,n);
return 0;
}
void array_printf(int a[],int n){
int i ;
for (i = 0; i < n; ++i)
{
printf("%d ",a[i]);
}
printf("\n");
}
void sort_heap(int a[],int n){
int i,x ;
for(i=n-1;i>0;i--){
build_heap(a,i);
x=a[0];
a[0] = a[i];
a[i] =x;
}
}
void build_heap(int a[],int e){
int r,i;
int x;
for(i=e;i>=1;i--){
r=(i-1)/2;
if(a[r]<a[i]){
x=a[r];
a[r] =a[i];
a[i] = x;
}
}
}
java代码
import java.util.List;public class SortHeap implements Sort {
@Override
public void sort(List<Integer> source) {
for(int i = source.size()-1 ; i>0 ; i--){
build_heap(source, i);
switch_list_elements(source, 0, i);
}
}
private void build_heap(List<Integer> source, int e){
if(e>=source.size())
return;
for(int i = e; i>0 ; i--){
int root = (i-1)/2;
if(source.get(root)<source.get(i))
switch_list_elements(source, root, i);
}
}
private void switch_list_elements(List<Integer> source,int a, int b){
int x = source.get(a);
source.set(a, source.get(b));
source.set(b, x);
}
}
相关文章推荐
- [算法学习笔记]排序算法——堆排序
- 【算法学习】浅谈排序算法
- C#数据结构和算法学习系列四----基础排序算法
- 算法学习之堆排序(java实现)
- STL学习笔记----14.STL算法之 (排序算法)
- 数据结构与算法学习笔记——堆排序
- 算法导论之排序算法学习
- 算法分析学习笔记(三) - 排序算法(上)
- 算法学习笔记----第二部分:排序和顺序统计量----第6章、堆排序
- 算法学习之排序学习之堆排序和如何建堆
- 算法设计和数据结构学习_2(常见排序算法思想)
- STL学习笔记----14.STL算法之 (排序算法)
- 【算法分析】排序算法:希尔、归并、快速、堆排序
- 【算法学习】堆排序(Heap Sorting)
- 算法学习笔记----第二部分:排序和顺序统计量----第6章、堆排序
- 算法学习-排序算法-快速排序
- 算法学习之排序学习之堆排序和如何建堆
- 堆排序(Heap Sort)算法学习
- 算法学习记录-排序——堆排序
- 一步步学习数据结构和算法之堆排序效率分析及java实现