forked from DHEERAJHARODE/Hacktoberfest2024-Open-source-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbucket_sort.c
124 lines (95 loc) · 2.25 KB
/
bucket_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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include<stdio.h>
#include<stdlib.h>
typedef struct Bnode{
double data;
struct Bnode* next;
} bnode;
int Nbucket = 10;
int interval = 10;
int getIdx(int n){
return(n*interval);
}
void printBuckets(bnode* head){
bnode* temp = head;
while(temp != NULL){
printf("%lf ->",temp->data);
temp = temp->next;
}
}
bnode* insert_Sorted(bnode* shead , bnode* cur){
if(shead == NULL || shead->data >= cur->data){
cur->next = shead;
shead = cur;
return cur;
}
else{
bnode* temp = shead;
while((temp->next != NULL) && (temp->next->data < cur->data)){
temp = temp->next;
cur->next = temp->next;
temp->next = cur;
}
return shead;
}
}
bnode* insertionSort_ll(bnode* head){
//Insertion Sort linked list
bnode* cur = head;
bnode* shead = NULL;
while(cur != NULL){
bnode* next = cur->next;
shead = insert_Sorted(shead,cur);
cur = next;
}
return shead;
}
void bucketSort(double *arr,int n){
bnode** buc = (bnode**)malloc(sizeof(bnode*)*Nbucket);
for(int i = 0 ; i < Nbucket ; i++){
buc[i] = NULL;
}
for(int i = 0 ; i < n ; i++){
int pos = getIdx(arr[i]);
bnode* cur = (bnode*)malloc(sizeof(bnode));
cur->data = arr[i];
cur->next = buc[pos];
buc[pos] = cur;
}
//print buckets
for(int i = 0 ; i < Nbucket ; i++){
printf("Bucket[%d] = ",i);
printBuckets(buc[i]);
printf("\n");
}
for(int i = 0 ; i < Nbucket ; i++){
buc[i] = insertionSort_ll(buc[i]);
}
//print buckets(After Sorting)
for(int i = 0 ; i < Nbucket ; i++){
printf("Bucket[%d] = ",i);
printBuckets(buc[i]);
printf("\n");
}
int j = 0;
for(int i = 0 ; i < Nbucket ; i++){
bnode* temp = buc[i];
while(temp != NULL){
arr[j++] = temp->data;
temp = temp->next;
}
}
}
int main(){
int n;
scanf("%d",&n);
double arr[n];
for(int i = 0 ; i < n ; i++){
scanf("%lf",&arr[i]);
}
bucketSort(arr,n);
for(int i = 0 ; i < n ; i++){
printf("%lf ",arr[i]);
}
puts("");
return 0;
}