排序算法(堆排序)
2016-08-06 16:20
253 查看
堆排序是对选择排序的改进(时间复杂度和希尔排序一样O(nlog2n))
数据结构:完全二叉树(大顶堆,根节点都比左右节点大,小顶堆,根节点小于双亲节点)
public class HeapSort {
public static void main(String[] args) {
int a[]={1,2,4,9,33,2,6,7,10,11};
sort(a, 10);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
}
//调整堆
public static void heapAdjust(int a[],int s,int n){
int i,temp;
temp=a[s];
for(i=2*s;i<n;i*=2){
if(i+1<n&&a[i]<a[i+1]){
i++;
}
if(temp>=a[i]) break;
a[s]=a[i];
s=i;
}
a[s]=temp;
}
//交换位置
public static void swap(int a[],int i,int j){
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
//排序
public static void sort(int h[],int n){
int i;
for(i=n/2;i>0;i--){
heapAdjust(h, i, n);
}
for(i=n-1;i>1;i--){
swap(h, 1, i);
heapAdjust(h, 1, i-1);
}
}
}
数据结构:完全二叉树(大顶堆,根节点都比左右节点大,小顶堆,根节点小于双亲节点)
public class HeapSort {
public static void main(String[] args) {
int a[]={1,2,4,9,33,2,6,7,10,11};
sort(a, 10);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
}
//调整堆
public static void heapAdjust(int a[],int s,int n){
int i,temp;
temp=a[s];
for(i=2*s;i<n;i*=2){
if(i+1<n&&a[i]<a[i+1]){
i++;
}
if(temp>=a[i]) break;
a[s]=a[i];
s=i;
}
a[s]=temp;
}
//交换位置
public static void swap(int a[],int i,int j){
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
//排序
public static void sort(int h[],int n){
int i;
for(i=n/2;i>0;i--){
heapAdjust(h, i, n);
}
for(i=n-1;i>1;i--){
swap(h, 1, i);
heapAdjust(h, 1, i-1);
}
}
}
相关文章推荐
- 9种排序算法性能之比较之----堆排序
- 时间复杂度为O(N*logN)的排序算法——归并排序、快速排序、堆排序
- 排序算法之堆排序
- Java排序算法(二):堆排序
- 各种排序算法实现——基数排序、归并排序、插入排序、冒泡排序、选择排序、快速排序、堆排序、希尔排序
- 经典排序算法 - 堆排序Heap sort
- 几种常用的排序算法的分析及java实现(希尔排序,堆排序,归并排序,快速排序,选择排序,插入排序,冒泡排序)
- 排序算法之四--堆排序
- 排序算法之(7)——堆排序
- 排序算法之堆排序 Heap Sort
- python排序算法-冒泡排序,选择排序,直接插入排序,希尔排序,归并排序,快速排序,堆排序
- 八种常见排序算法:插入、冒泡、选择、希尔、归并、快排、堆排序、基数排序
- 常见的五类排序算法图解和实现(选择类:简单选择排序,锦标赛排序,树形选择排序,堆排序)
- 排序算法之堆排序
- 排序算法:堆排序
- 排序算法-堆排序
- 排序算法复习(Java实现)(二): 归并排序,堆排序,桶式排序,基数排序
- 堆排序----排序算法
- 排序算法2--简单选择排序、堆排序
- 排序算法2--简单选择排序、堆排序