Skip to content

Commit 7b2f093

Browse files
committed
Bucketsort c implementation
1 parent 91f2c2c commit 7b2f093

File tree

1 file changed

+110
-0
lines changed

1 file changed

+110
-0
lines changed

Sorting/bucketsort.c

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <time.h>
4+
5+
#define MAX 1000000
6+
7+
8+
void ler(int arr[], int n)
9+
{
10+
int i;
11+
for(i = 0; i < n; i++)
12+
{
13+
arr[i] = rand() % n;
14+
}
15+
}
16+
17+
void print(int arr[], int n, char mens[])
18+
{
19+
int i;
20+
printf("%s\n",mens);
21+
for(i = 0; i < n; i++)
22+
{
23+
printf("%d ", arr[i]);
24+
if(i % 50 == 0 && i > 0) printf("\n");
25+
}
26+
printf("\n");
27+
}
28+
typedef struct no
29+
{
30+
int valor;
31+
struct no* prox;
32+
}No;
33+
34+
void inserir(No** r, int valor)
35+
{
36+
No* p;
37+
No* aux = NULL;
38+
No* atual = (*r);
39+
int cond = 1;
40+
41+
p = (No*)malloc(sizeof(No));
42+
43+
p->valor = valor;
44+
p->prox = NULL;
45+
46+
while(atual != NULL && cond)
47+
{
48+
if(valor < atual->valor) cond = 0;
49+
else
50+
{
51+
aux = atual;
52+
atual = atual->prox;
53+
}
54+
}
55+
p->prox = atual;
56+
if(aux == NULL) (*r) = p;
57+
else aux->prox = p;
58+
}
59+
60+
void bucketSort(int arr[], int n)
61+
{
62+
No** bucket = (No**)malloc(n * sizeof(No*));
63+
printf("------------------BUCKETSORT------------------\n");
64+
int i,j;
65+
for(i = 0; i < n; i++)
66+
{
67+
bucket[i] = NULL;
68+
}
69+
for(i = 0; i < n; i++)
70+
{
71+
int indice = n * ((double) arr[i]/(n + 1));
72+
inserir(bucket+indice, arr[i]);
73+
74+
}
75+
int ind = 0;
76+
No* b;
77+
for(i = 0; i < n; i++)
78+
{
79+
b = bucket[i];
80+
while(b != NULL)
81+
{
82+
arr[ind++] = (b)->valor;
83+
bucket[i] = (b)->prox;
84+
free(b);
85+
b = bucket[i];
86+
}
87+
free(b);
88+
}
89+
}
90+
/*------------------------------------------*/
91+
int main()
92+
{
93+
srand(time(NULL));
94+
int n;
95+
printf("Input the array size\n");
96+
scanf("%d",&n);
97+
int *arr = malloc(sizeof(int)*n);
98+
99+
100+
101+
ler(arr, n);
102+
print(arr, n, "Antes");
103+
printf("\n");
104+
bucketSort(arr, n);
105+
printf("\n");
106+
print(arr, n, "Depois");
107+
printf("\n\n");
108+
109+
return 0;
110+
}

0 commit comments

Comments
 (0)