championship
If you want to select the first and second largest data from n data (requires the location and value of the output data), what method is used to compare the least number of times? We can be inspired by sports championships.
As shown in the figure [1.png], in a tournament of 8 players, first catch and compare each other and eliminate half of them. The winners will compete again and again...until the first place is decided.
After the first place is output, just re-match the position marked in yellow.
The following code implements this algorithm (assuming that there is no same value in the data).
The code needs to use an array to represent the tree in the figure (note that this is a full binary tree, and the shortcomings need to be filled). It does not store the data itself, but stores the subscript of the data.
After the first data is output, its location is marked as -1class A{ //a represents the data to be processed, if the length is not a power of 2, the insufficient position is filled with -1 static void pick(int[] a) { int n = 1; while(n <a.length) n *= 2; int[] b = new int[2*n-1]; for(int i=0; i<n; i++){ if(i <a.length) b[n-1+i] = i; else b[n-1+i] = -1; }
//Process from the last one forward
for(int i=b.length-1; i>0; i-=2){ if(b[i]<0){ if(b[i-1]>=0 ) b[(i-1)/2] = b[i-1]; else b[(i-1)/2] = -1; } else{ if(a[b[i]]>a[b [i-1]]) b[(i-1)/2] = b[i]; else b[(i-1)/2] = b[i-1]; } } //Output tree root System .out.println(b[0] + ": "+ a[b[0]]); //The position where the value is equal to the root element needs to be re-pk pk(a,b,0,b[0]); // Output tree root again
System.out.println(b[0] + ": " + a[b[0]]);
}
// a represents the data to be processed, b binary tree, k is the current position to be compared, and v has decided the value of the
winner static void pk(int[] a, int[] b, int k, int v)
{ int k1 = k *2+1; int k2 = k1 + 1; if(k1>=b.length || k2>=b.length){ b[k] = -1; return; } if(b[k1]==v ) pk(a,b,k1,v); else pk(a,b,k2,v); //Re-compare if(b[k1]<0){ if(b[k2] >= 0) b[ k] = b[k2]; else b[k] = -1; return; }
if(b[k2]<0){
if(b[k1]>=0)
b[k] = b[k1];
else
b[k] = -1;
return;
}if(__________________________) //填空
b[k] = b[k1];
else
b[k] = b[k2];
}
};
Please analyze the process carefully and fill in the missing code.
Submit the answer through the browser, only fill in the missing code, do not fill in the existing code or other descriptive sentences, etc.