堆排序

public class heap_Sort {
    
    
    int a []={12,34,543,21,543,645,65,254767,54,7687,9808,234};
    public heap_Sort(){
        heapsort(a);
        
    }

    
    public void heapsort(int[] a){
        
        int alengh=a.length;
        
        for (int i=0;i<alengh;i++){
            
            buildMaxHeap(a,alengh-1-i);
            
        }    
        
    }
    
    
    
    
    //
    private void buildMaxHeap(int [] data,int lastindex){
        
        for(int i=(lastindex-1)/2;i>=0;i--){
            
            int k=i;
            while(k*2+1<=lastindex){
                int bigindex=2*k+1;
                
                if(bigindex<lastindex){
                    
                    if(data[bigindex]<data[bigindex+1]){
                        
                        
                        bigindex++;
                    }
                    
                }
                if(data[k]<data[bigindex]){
                    
                    swap(data,k,bigindex);
                    k=bigindex;
                }else{break;}
                
                
            }
            
            
        }
        
        
    }
    
    //
    private void swap(int [] data,int i,int j){
        
        int tmp=data[i];
        data[i]=data[j];
        data[j]=tmp;
        
    }
}

 

posted on 2016-11-28 11:30  猫儿爹  阅读(172)  评论(0编辑  收藏  举报

导航