-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_sort.c~
executable file
·90 lines (84 loc) · 1.16 KB
/
merge_sort.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
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
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
void merge(int A[], int B[], int C[], int na, int nb, int nc)
{
//A e B sottoarray ordinati, in C la fusione
int i=0,j=0,k=0;
while(i < na && j < nb)
{
if(A[i] >= B[j])
{
C[k] = B[j];
j++;
}
else
{
C[k] = A[i];
i++;
}
k++;
}
if(i == na && j < nb)
{
while(j < nb)
{
C[k] = B[j];
j++;
k++;
}
}
if(j == nb && i < na)
{
while(i < na)
{
C[k] = A[i];
i++;
k++;
}
}
}
void merge_sort(int A[], int n)
{
int m,h,k,B[100],C[100];
if(n > 1)
{
m = n/2;
for(h = 0; h < m; h++)
B[h] = A[h];
for(k = m; k < n; k++)
C[k-m] = A[k];
merge_sort(B,h);
merge_sort(C,k);
merge(B,C,A,h,k,n);
}
}
void visua(int A[], int n)
{
int i;
printf("[");
for(i = 0; i < n-1; i++)
{
printf("%d,",A[i]);
}
printf("%d]\n", A[n-1]);
}
int main()
{
int n,i,tmp;
int A[100];
printf("Inserisci n: ");
scanf("%d",&n);
for(i = 0; i < n; i++)
{
printf("Inserisci un elemento: ");
scanf("%d",&A[i]);
//A[i] = rand();
}
printf("\nArray non ordinato: \n");
visua(A,n);
merge_sort(A,n);
printf("Array ordinato: \n");
visua(A,n);
}