forked from CodersForLife/Data-Structures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbucketsort.c
More file actions
110 lines (96 loc) · 1.59 KB
/
Copy pathbucketsort.c
File metadata and controls
110 lines (96 loc) · 1.59 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 1000000
void ler(int arr[], int n)
{
int i;
for(i = 0; i < n; i++)
{
arr[i] = rand() % n;
}
}
void print(int arr[], int n, char mens[])
{
int i;
printf("%s\n",mens);
for(i = 0; i < n; i++)
{
printf("%d ", arr[i]);
if(i % 50 == 0 && i > 0) printf("\n");
}
printf("\n");
}
typedef struct no
{
int valor;
struct no* prox;
}No;
void inserir(No** r, int valor)
{
No* p;
No* aux = NULL;
No* atual = (*r);
int cond = 1;
p = (No*)malloc(sizeof(No));
p->valor = valor;
p->prox = NULL;
while(atual != NULL && cond)
{
if(valor < atual->valor) cond = 0;
else
{
aux = atual;
atual = atual->prox;
}
}
p->prox = atual;
if(aux == NULL) (*r) = p;
else aux->prox = p;
}
void bucketSort(int arr[], int n)
{
No** bucket = (No**)malloc(n * sizeof(No*));
printf("------------------BUCKETSORT------------------\n");
int i,j;
for(i = 0; i < n; i++)
{
bucket[i] = NULL;
}
for(i = 0; i < n; i++)
{
int indice = n * ((double) arr[i]/(n + 1));
inserir(bucket+indice, arr[i]);
}
int ind = 0;
No* b;
for(i = 0; i < n; i++)
{
b = bucket[i];
while(b != NULL)
{
arr[ind++] = (b)->valor;
bucket[i] = (b)->prox;
free(b);
b = bucket[i];
}
free(b);
}
}
/*------------------------------------------*/
int main()
{
srand(time(NULL));
int n;
printf("Input the array size\n");
scanf("%d",&n);
int *arr = malloc(sizeof(int)*n);
ler(arr, n);
print(arr, n, "Antes");
printf("\n");
bucketSort(arr, n);
printf("\n");
print(arr, n, "Depois");
printf("\n\n");
return 0;
}