数据结构排序问题---堆排序及各种排序时间空间复杂度
2014-10-24 16:11
435 查看
堆排序基本思路:根据完全二叉树,建立最大最小堆来排序
时间复杂度:O(nlongn)
各种排序复杂度:
具体分析:http://blog.sina.com.cn/s/blog_771849d301010ta0.html
时间复杂度:O(nlongn)
/** * */ package com; /** * @author wenb * @time 下午03:52:55 * @date 2014-10-24 */ public class HeapSort { public static void main(String args[]){ int[] a = {1,3,2,21,5,12,98,54}; headSort(a); for(int i=0;i<a.length;i++){ System.out.print(a[i]+" "); } } public static int[] headSort(int[] sortArray){ for(int i=0;i<sortArray.length-1;i++){ buildMaxHeap(sortArray,sortArray.length-1-i); swap(sortArray,0,sortArray.length-1-i); } return sortArray; } //交换两个数据的方法 public static void swap(int[] data,int i,int j){ int temp = data[i]; data[i] = data[j]; data[j] = temp; } //建立最大堆 public static void buildMaxHeap(int[] data,int lastIndex){ //从lastIndex节点的父节点开始舰堆 for(int i=(lastIndex-1)/2;i>=0;i--){ //保存正在判断的节点 int k = i; //这里为每个节点建立大顶堆,只要这个根节点还有子节点 while((2*k+1) <= lastIndex){ //假设左节点的值时最大的 int biggerIndex = 2*k+1; //说明还有右节点是存在的 if(biggerIndex < lastIndex){ //选出子节点中最大的值 if(data[biggerIndex] < data[biggerIndex+1]){ biggerIndex++; } } //将跟节点与子节点进行比较 if(data[k] < data[biggerIndex]){ swap(data,k,biggerIndex); k = biggerIndex; }else{ break; } } } } }
各种排序复杂度:
具体分析:http://blog.sina.com.cn/s/blog_771849d301010ta0.html
相关文章推荐
- 各种排序的时间复杂度和空间复杂度
- 一道时间复杂度为O(N)空间复杂度为O(1)的排序问题
- 排序问题:各种排序算法的时间复杂度 比较
- 各种排序时间空间复杂度稳定性分析
- 排序问题思考(要求时间和空间复杂度尽可能的低)【Part 1】
- 各种排序方法的时间复杂度、空间复杂度和稳定性统计表
- 数据结构中排序和查找各种时间复杂度
- 数据结构-算法效率的度量-时间复杂度和空间复杂度
- 各种查找和排序的定义及时间复杂度
- java 快速排序 时间复杂度 空间复杂度 稳定性
- 数据结构之时间复杂度和空间复杂服
- 排序的时间复杂度为O(n),空间复杂度为O(1)
- 数据结构中排序和查找各种时间复杂度
- 数据结构--各种排序的实现(排序小结 希尔排序 快排 堆排序 归并排序)
- PHP数据结构(3) 选择排序机器时间复杂度
- 堆的建立、堆排序的时间复杂度问题
- 各种数据结构insert和search操作的平均时间复杂度比较
- 各种排序算法时间复杂度、空间复杂度比较
- 题目:某公司有几万名员工,请完成一个时间复杂度为O(n)的算法对该公司员工的年龄作排序,可使用O(1)的辅助空间。
- 数据结构(C#)--冒泡、插入、快速、堆、归并、希尔、选择各种排序排序过程比较以及各种排序的所用时间的对比