abouttr3

heapSort

Apr 25th, 2013
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.25 KB | None | 0 0
  1. public class Array{
  2.  
  3.     public static void heapsort(int []list){
  4.         heap(list);
  5.         for(int i=(list.length-1);i>0;i--){
  6.             exchange(list,0,i);// exchange root (index 0) with last element in heap tree
  7.             sort(list,0,i);
  8.         }
  9.  
  10.     }
  11.  
  12.     public static void heap(int []list){//for build heap
  13.         for(int i=(list.length-2)/2;i>=0;i--){
  14.             System.out.println(i);
  15.             sort(list,i,list.length);
  16.         }
  17.     }
  18.  
  19.     public static void sort(int []list,int parent,int last){// arrange - bigger child will be new parent
  20.         int i=parent*2+1;
  21.         int j=parent*2+2;
  22.         int big=parent;
  23.         if(i<last){
  24.             if(list[i]>list[big]){//if left child largest than parent
  25.                 big=i;
  26.             }
  27.         }
  28.         if(j<last){
  29.             if(list[j]>list[big]){//if right child largest than parent and left child
  30.                 big=j;
  31.             }
  32.         }
  33.         if(big!=parent){
  34.             exchange(list,parent,big);// exchange parent with largest child
  35.             sort(list,big,last); //recursion
  36.         }
  37.     }
  38.  
  39.     public static  void exchange(int []list,int i, int j){
  40.         int temp=list[i];
  41.         list[i]=list[j];
  42.         list[j]=temp;
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment