I've coded up the Heap Sort algorithm, but I'm having a hard time deciding what should be considered a comparison. I assumed the following would contribute towards the comparisons but the results I obtain seem off to me (by a lot maybe?) here's the code
public class heapsort{
static int counter = 0;
public static void main(String[] args) {
//int[] a1={1, 16, 2, 3, 14, 4, 5, 12, 7, 10, 8, 9, 17, 19, 21, 23, 26, 27};
int[] a1 = {1, 2};
System.out.println(sort(a1));
for(int i=0;i<a1.length;i++){
System.out.print(a1[i] + " ");
}
}
private static int[] a;
private static int n;
private static int left;
private static int right;
private static int largest;
public static void buildheap(int[] a){
n= a.length-1;
for(int i= n/2; i >= 0; --i){
maxheap(a,i);
}
}
public static void maxheap(int[] a, int i){
left=2*i;
right=2*i+1;
if(left <= n && a[left] > a[i]){
counter++;
largest=left;
}
else{
counter++;
largest=i;
}
if(right <= n && a[right] > a[largest]){
counter++;
largest=right;
}
if(largest!=i){
counter++;
exchange(i,largest);
maxheap(a, largest);
}
}
public static void exchange(int i, int j){
int t=a[i];
a[i]=a[j];
a[j]=t;
}
public static int sort(int []a0){
a=a0;
buildheap(a);
for(int i=n;i>0; --i){
exchange(0, i);
n=n-1;
maxheap(a, 0);
}
return counter;
}
}
I know some of the counters might be wrong, suggestions?
Count comparisons of your array, sometimes/always "a". EG: "a[left] > a[i]". You could add a counter for the comparisons as a global, and ++ it each time you do a comparison to get a comparison count.
BTW, heap sort is interesting theoretically, but it's not stable, and isn't generally as fast as timsort, nor does it take advantage of partially sorted data as well.