Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Array{
- public static void heapsort(int []list){
- heap(list);
- for(int i=(list.length-1);i>0;i--){
- exchange(list,0,i);// exchange root (index 0) with last element in heap tree
- sort(list,0,i);
- }
- }
- public static void heap(int []list){//for build heap
- for(int i=(list.length-2)/2;i>=0;i--){
- System.out.println(i);
- sort(list,i,list.length);
- }
- }
- public static void sort(int []list,int parent,int last){// arrange - bigger child will be new parent
- int i=parent*2+1;
- int j=parent*2+2;
- int big=parent;
- if(i<last){
- if(list[i]>list[big]){//if left child largest than parent
- big=i;
- }
- }
- if(j<last){
- if(list[j]>list[big]){//if right child largest than parent and left child
- big=j;
- }
- }
- if(big!=parent){
- exchange(list,parent,big);// exchange parent with largest child
- sort(list,big,last); //recursion
- }
- }
- public static void exchange(int []list,int i, int j){
- int temp=list[i];
- list[i]=list[j];
- list[j]=temp;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment