
/******************************************************************************
* MODULE     : merge_sort
* COPYRIGHT  : (C) 1999  Joris van der Hoeven
*******************************************************************************
* This software falls under the GNU general public license and comes WITHOUT
* ANY WARRANTY WHATSOEVER. See the file $TEXMACS_PATH/LICENSE for more details.
* If you don't have this file, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
******************************************************************************/

#include <array.gen.h>

#module code_merge_sort (T)
#import array (T)

array<T> merge_buf<T>;

static void
merge_sort (array<T>& a, int start, int end) {
  if (end-start<=1) return;
  if (end-start==2) {
    if (!(a[start]<=a[start+1])) {
      merge_buf<T>[start]=a[start];
      a[start]=a[start+1];
      a[start+1]=merge_buf<T>[start];
    }
    return;
  }
  int middle=(start+end)>>1; 
  merge_sort(a,start,middle);
  merge_sort(a,middle,end);
  int i,j,k;
  for (i=start, j=middle, k=start; (i<middle) && (j<end); )
    if (a[i]<=a[j]) merge_buf<T>[k++]=a[i++];
    else            merge_buf<T>[k++]=a[j++];
  j=k;
  while (i!=middle) a[k++]=a[i++];
  for (i=start; i<j; i++) a[i]=merge_buf<T>[i];
}

void
merge_sort (array<T>& a) {
  merge_buf<T>= array<T> (N(a));
  merge_sort (a, 0, N(a));
  merge_buf<T>= array<T> ();
}

#endmodule // code_merge_sort (T)
