2 * Re-entrant mergesort.
3 * Copyright (c) 1998 New Generation Software (NGS) Oy
5 * Author: Markku Rossi <mtr@ngs.fi>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Library General Public
11 * License as published by the Free Software Foundation; either
12 * version 2 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Library General Public License for more details.
19 * You should have received a copy of the GNU Library General Public
20 * License along with this library; if not, write to the Free
21 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
26 * $Source: /cygdrive/c/RCVS/CVS/ReactOS/reactos/lib/kjs/src/mrgsort.c,v $
37 * Types and definitions.
40 #define COPY(buf1, idx1, buf2, idx2) \
41 memcpy ((buf1) + (idx1) * size, (buf2) + (idx2) * size, size);
48 do_mergesort (unsigned char *base
, unsigned int size
, unsigned char *tmp
,
49 unsigned int l
, unsigned int r
,
50 MergesortCompFunc func
, void *func_ctx
)
52 unsigned int i
, j
, k
, m
;
58 do_mergesort (base
, size
, tmp
, l
, m
, func
, func_ctx
);
59 do_mergesort (base
, size
, tmp
, m
+ 1, r
, func
, func_ctx
);
61 memcpy (tmp
+ l
* size
, base
+ l
* size
, (r
- l
+ 1) * size
);
68 while (i
<= m
&& j
<= r
)
70 if ((*func
) (tmp
+ i
* size
, tmp
+ j
* size
, func_ctx
) <= 0)
72 COPY (base
, k
, tmp
, i
);
77 COPY (base
, k
, tmp
, j
);
83 /* Copy left-overs. Only one of the following will be executed. */
86 COPY (base
, k
, tmp
, i
);
91 COPY (base
, k
, tmp
, j
);
102 mergesort_r (void *base
, unsigned int number_of_elements
,
103 unsigned int size
, MergesortCompFunc comparison_func
,
104 void *comparison_func_context
)
108 if (number_of_elements
== 0)
111 /* Allocate tmp buffer. */
112 tmp
= malloc (number_of_elements
* size
);
113 assert (tmp
!= NULL
);
115 do_mergesort (base
, size
, tmp
, 0, number_of_elements
- 1, comparison_func
,
116 comparison_func_context
);