-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathmergesort.c
50 lines (43 loc) · 1 KB
/
mergesort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
* Copyright(C) 2020, Bruno César Ribas <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2.1 of the GNU Lesser General Public License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#include "mergesort.h"
#include "mergesort.h"
#include <stdlib.h>
void merge(Item *V, int l, int m, int r)
{
Item *R=malloc(sizeof(Item)*(r-l+1));
int i=l,j=m+1,k=0;
while(i<=m && j<=r)
{
if(lesseq(V[i],V[j]))
R[k++]=V[i++];
else
R[k++]=V[j++];
}
while(i<=m)
R[k++]=V[i++];
while(j<=r)
R[k++]=V[j++];
k=0;
for(i=l;i<=r;i++)
V[i]=R[k++];
free(R);
}
void mergesort(Item *V,int l, int r)
{
if (l>= r) return;
int meio=(l+r)/2;
mergesort(V,l,meio);
mergesort(V,meio+1,r);
merge(V,l,meio,r);
}