Code Fragment: MergeSort



template <typename Object, typename Sequence>
class MergeSort {
protected:   						// utility functions
  void merge(Sequence& S1, Sequence& S2, Sequence& S);	// merge utility
  void appendFirst(Sequence& src, Sequence& dst) {	// append utility
    Object obj = src.first().element();			// first of source
    src.remove(src.first());				// remove it
    dst.insertLast(obj);				// append to dest
  }
public:
  void mergeSort(Sequence& S);				// merge sort S
};
template <typename Object, typename Sequence>
void MergeSort<Object, Sequence>::
merge(Sequence& S1, Sequence& S2, Sequence& S) {	// merge S1 and S2 to S
  while(!S1.isEmpty() && !S2.isEmpty())			// until either is empty
    if(S1.first().element() <= S2.first().element())	// copy smaller element
      appendFirst(S1, S);
    else
      appendFirst(S2, S);
  while(!S1.isEmpty())					// copy remainder of S1
    appendFirst(S1, S);
  while(!S2.isEmpty())					// copy remainder of S2
    appendFirst(S2, S);
}
template <typename Object, typename Sequence>
void MergeSort<Object, Sequence>::
mergeSort(Sequence& S) {				// sort S
  Sequence S1, S2;
  int i;
  int n = S.size();
  if (n <= 1) return;					// 0 or 1 elements
  for (i = n  ; i > n/2  ; i--) appendFirst(S, S1);	// put half in S1
  for (       ; i > 0    ; i--) appendFirst(S, S2);	// put remainder in S2
  mergeSort(S1);					// sort S1
  mergeSort(S2);					// sort S2
  merge(S1, S2, S);					// merge S1 and S2 into S
}