-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExercises-MergeSort.c
More file actions
93 lines (74 loc) · 1.58 KB
/
Copy pathExercises-MergeSort.c
File metadata and controls
93 lines (74 loc) · 1.58 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include<stdio.h>
#define TAM 30
void merge(int*,int,int,int);
void mergeSort(int*,int,int);
int main()
{
int vetor[TAM];
int iFor;
printf("Insira os elementos do vetor:\n");
for(iFor = 0; iFor < TAM; iFor++){
scanf("%d",&vetor[iFor]);
}
mergeSort(vetor,0,TAM-1);
printf("Elementos do vetor em ordem ascendente:\n");
for (iFor = 0; iFor < TAM; iFor++) {
printf("%d ",vetor[iFor]);
}
return 0;
}
void mergeSort(int *vetor,int Lvetor,int Rvetor)
{
if (Lvetor < Rvetor)
{
int meio = (Lvetor + Rvetor) / 2;
mergeSort(vetor,Lvetor,meio);
mergeSort(vetor,meio+1,Rvetor);
merge(vetor,Lvetor,meio,Rvetor);
}
}
void merge(int *vetor,int Lvetor,int meio,int Rvetor)
{
int iFor,jFor,kFor;
const int n1 = meio - Lvetor + 1;
const int n2 = Rvetor - meio;
int Laux[n1];
int Raux[n2];
for (iFor = 0; iFor < n1; iFor++)
{
Laux[iFor] = vetor[Lvetor + iFor];
}
for (jFor = 0; jFor < n2; jFor++)
{
Raux[jFor] = vetor[meio + 1 + jFor];
}
iFor = 0;
jFor = 0;
kFor = Lvetor;
while (iFor < n1 && jFor < n2)
{
if (Laux[iFor] <= Raux[jFor])
{
vetor[kFor] = Laux[iFor];
iFor++;
}
else
{
vetor[kFor] = Raux[jFor];
jFor++;
}
kFor++;
}
while (iFor < n1)
{
vetor[kFor] = Laux[iFor];
iFor++;
kFor++;
}
while (jFor < n2)
{
vetor[kFor] = Raux[jFor];
jFor++;
kFor++;
}
}