Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class heapsort {
- private int h[];
- private int heapSize; // the number of items stored in h
- public static final int CAPACITY = 100;
- public heapsort(int[] A, int n) {
- //Initialize h of size CAPACITY
- h = new int [CAPACITY];
- //Copy A into h
- for(int i=1; i<=n; i++)
- h[i]=A[i-1];
- System.out.println("input1.txt:");
- print(h,n);
- Heapsort(h,n);
- //BuildMaxHeap();
- }
- public int[] Heapsort(int[] h, int n){
- int temph[]; //array to be outputed at each extract
- int newh[];//max numbers inserted
- temph = new int [CAPACITY];
- newh = new int [CAPACITY];
- int tempValue=0;
- for(int i=1; i<n; i++){
- tempValue = heapMax(h);
- heapExtractMax(h,n);
- newh[i] = tempValue;
- for(int j=1; j<=n; j++)
- temph[j]=h[j];
- for(int k=1; k<=i; k++){
- temph[n-k+1]= newh[k];
- }
- print(temph,n);
- }
- return newh;
- }
- public void BuildMaxHeap(int[] h,int n){
- for (int i = (n/2); i >= 1; i--)
- MaxHeapify(h,i);
- }
- public void MaxHeapify(int[] h,int index){
- int tempp = h[index];
- int templ = h[2*index];
- int tempr = h[2*index+1];
- if(tempp<templ||tempp<tempr){
- if(templ>tempr||tempr==0){
- if(templ!=0){
- h[2*index] = tempp;
- h[index] = templ;
- int tdl = 2*index;
- if(h[tdl]<h[2*tdl]||h[tdl]<h[2*tdl+1])//follow trickle all the way down
- MaxHeapify(h,tdl);
- }
- }
- else{
- if(tempr!=0){
- h[2*index+1] = tempp;
- h[index] = tempr;
- int tdr = 2*index+1;
- if(h[tdr]<h[2*tdr]||h[tdr]<h[2*tdr+1])
- MaxHeapify(h,tdr);
- }
- }
- }
- }
- public void heapExtractMax(int[] h,int n){//---------------------------------------------------------------------------------------void heapExtractMax
- if(h[1]==0){
- throw new IndexOutOfBoundsException("MaxHeap empty.");
- }
- else{
- int temp = h[n];
- h[1] = temp;
- h[n+1]=0;
- BuildMaxHeap(h,n);
- }
- }
- public int heapMax(int[] h){//--------------------------------------------------------------------------------------------int heapMax
- if(h[1]==0){
- throw new IndexOutOfBoundsException("heapMax empty.");
- }
- return h[1];
- }
- public void print(int[] h,int n){//----------------------------------------------------------------------------------void print
- int i = n;
- while (i!=0){
- if(h[n-i+1]!=0){
- System.out.print(h[n-i+1]+" ");
- }
- i--;
- }
- System.out.println("");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment