zoukankan      html  css  js  c++  java
  • 数据结构排序问题---堆排序及各种排序时间空间复杂度

    堆排序基本思路:根据完全二叉树,建立最大最小堆来排序

    时间复杂度: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

    奋斗奋斗奋斗奋斗奋斗奋斗奋斗奋斗生命在于奋斗,也为自己带盐奋斗奋斗奋斗奋斗奋斗奋斗奋斗奋斗
  • 相关阅读:
    Realtime crowdsourcing
    maven 常用插件汇总
    fctix
    sencha extjs4 command tools sdk
    首次吃了一颗带奶糖味的消炎药,不知道管用不
    spring mvc3 example
    ubuntu ati driver DO NOT INSTALL recommand driver
    yet another js editor on windows support extjs
    how to use springsource tools suite maven3 on command
    ocr service
  • 原文地址:https://www.cnblogs.com/hardwork/p/4048587.html
Copyright © 2011-2022 走看看