Last change
on this file since a0bcf1 was a0bcf1, checked in by Frederik Heber <heber@…>, 17 years ago |
-initial commit
-Minimum set of files needed from ESPACK SVN repository
-Switch to three tantamount package parts instead of all relating to pcp (as at some time Ralf's might find inclusion as well)
|
-
Property mode
set to
100644
|
File size:
1.4 KB
|
Rev | Line | |
---|
[a0bcf1] | 1 | /*
|
---|
| 2 | Project: CP
|
---|
| 3 | Jan Hamaekers
|
---|
| 4 | 2000
|
---|
| 5 |
|
---|
| 6 | File: Mergesort
|
---|
| 7 | Usage:
|
---|
| 8 | Insert in your Code
|
---|
| 9 | #include"mergesort.h"
|
---|
| 10 | double GetKey(void *Element) { } ...
|
---|
| 11 |
|
---|
| 12 |
|
---|
| 13 | Use:
|
---|
| 14 | naturalmergesort(a,l,r,&GetKey)
|
---|
| 15 | struct Element** a
|
---|
| 16 | int l,r
|
---|
| 17 |
|
---|
| 18 | See also: GetCrd.c
|
---|
| 19 | */
|
---|
| 20 |
|
---|
| 21 | #include<stdlib.h>
|
---|
| 22 |
|
---|
| 23 | void merge(void **a, int l, int m, int r, void **b, double (*GetKey)(void *)) {
|
---|
| 24 | /* merge two sorted sequnces
|
---|
| 25 | a[l]...a[m] and a[m+1]...a[r] -> a[l]...a[r]
|
---|
| 26 | b dummyarray (size b = r-l+1)*/
|
---|
| 27 | int h,i=l,j=m+1,k=l;
|
---|
| 28 | while (i <= m && j <= r) {
|
---|
| 29 | if (GetKey(a[i]) <= GetKey(a[j])) {
|
---|
| 30 | b[k]=a[i];
|
---|
| 31 | i++;
|
---|
| 32 | } else {
|
---|
| 33 | b[k] = a[j];
|
---|
| 34 | j++;
|
---|
| 35 | }
|
---|
| 36 | k++;
|
---|
| 37 | }
|
---|
| 38 | if (i > m) {
|
---|
| 39 | for (h=j; h <=r;h++) b[k+h-j] = a[h];
|
---|
| 40 | } else {
|
---|
| 41 | for (h=i; h <=m;h++) b[k+h-i] = a[h];
|
---|
| 42 | }
|
---|
| 43 | for (h=l; h <= r; h++) a[h] = b[h];
|
---|
| 44 | }
|
---|
| 45 |
|
---|
| 46 | void naturalmergesort(void **a, int l, int r, double (*GetKey)(void *)) {
|
---|
| 47 | /* sort a[l]...a[r]
|
---|
| 48 | !!! Nutzt vorhandenen Teilfolgen aus !!!
|
---|
| 49 | C_min = O(N)
|
---|
| 50 | C_max = O(N)
|
---|
| 51 | */
|
---|
| 52 | int ll=0, mm=0, rr=0;
|
---|
| 53 | void **b = (void **) malloc(sizeof(void *)*(r-l+1));
|
---|
| 54 | do {
|
---|
| 55 | rr = l-1;
|
---|
| 56 | while (rr < r) {
|
---|
| 57 | ll = rr+1;
|
---|
| 58 | mm = ll;
|
---|
| 59 | while (mm < r && GetKey(a[mm+1]) >= GetKey(a[mm])) mm++;
|
---|
| 60 | if (mm < r) {
|
---|
| 61 | rr = mm+1;
|
---|
| 62 | while (rr<r && GetKey(a[rr+1]) >= GetKey(a[rr])) rr++;
|
---|
| 63 | merge(a,ll,mm,rr,b,GetKey);
|
---|
| 64 | } else {
|
---|
| 65 | rr = mm;
|
---|
| 66 | }
|
---|
| 67 | }
|
---|
| 68 | } while (ll != l);
|
---|
| 69 | free(b);
|
---|
| 70 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.