Const intMaxvalue=999;//Select the maximum value according to the actual situationvoidKwaymerge (Element *r,intk) { inti,q; R=NewELEMENT[K];//K Records in the loser tree int*key=New int[k +1];//k sorting codes and build units Key[k] int*loser=New int[K];//k-1 a loser and a champion loser[0] for(i=0; i<k; i++) {//enter the first record and its sort code from the K merge segmentInputrecord (R[i]); Key[i]=R[i].key; } for(i=0; i<k; i++) loser[i]=k;//loser Tree all nodes are assigned K, representing the K-merge segment.key[k]=-MaxValue; for(i=k-1; i>=0; i--) adjust (key,loser,k,i);//from key[k-1] from ~key[0] to adjust to form the loser tree while(key[loser[0]]!=maxvalue) {//when MaxValue rise to loser[0] merge completeq=loser[0];//take the current minimum key code the merge segment number to send QOutputrecord (R[q]);//R[q] Write to output merge segmentInputrecord (R[q]);//read the next record from the first Q merge sectionkey[q]=R[q].key; Adjust (key,loser,k,q); //adjusted to the loser tree from Key[q]} Output end of run marker; //output segment End flag Delete[]r; Delete[]k; Delete[]loser;}voidAdjustintKey[];intLoser[];intKintq) { for(intt= (K+Q)/2; T>0; T/=2) if(key[loser[t]]<Key[q]) { inttemp=Q; Q=Loser[t]; Loser[t]=temp; } loser[0]=q;}
Algorithms-Sort (1) k-way balance merge with loser Tree