我已经编写了堆排序算法,但我很难决定应该将什么视为比较。我认为以下内容会有助于比较,但我获得的结果对我来说似乎很不合适(可能很多?)这是代码
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;
}
}
我知道一些柜台可能是错误的,建议?