-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap_sort.c~
executable file
·95 lines (84 loc) · 1.23 KB
/
heap_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
91
92
93
94
95
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int PARENT(int i)
{
return i/2;
}
int LEFT(int i)
{
return i*2;
}
int RIGHT(int i)
{
return (i*2)+1;
}
void swap(int A[],int i,int j)
{
int t;
t = A[i];
A[i] = A[j];
A[j] = t;
}
//TUTTI GLI INDICI PARTONO DA 1
void MAX_HEAPIFY(int A[], int i, int n, int hs)
{
int l = LEFT(i);
int r = RIGHT(i);
int max = i;
if(A[i-1] < A[l-1] && l <= hs)
max = l;
if(A[max-1] < A[r-1] && r <= hs)
max = r;
if(max != i)
{
swap(A,i,max);
MAX_HEAPIFY(A,max,n,hs);
}
}
void BUILD_MAX_HEAP(int A[], int n, int hs)
{
int i;
for(i = (n/2); i > 0; i--)
MAX_HEAPIFY(A,i-1,n,hs);
}
void HEAP_SORT(int A[], int n)
{
int hs = n,i;
BUILD_MAX_HEAP(A,n,hs);
for(i = n; i > 1; i--)
{
swap(A,0,i-1);
hs--;
MAX_HEAPIFY(A,1,n,hs);
}
}
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);
HEAP_SORT(A,n);
printf("Array ordinato: \n");
visua(A,n);
}