-
Notifications
You must be signed in to change notification settings - Fork 0
/
bucket-sort.cpp
110 lines (94 loc) · 1.95 KB
/
bucket-sort.cpp
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 <iostream>
#include <math.h>
using namespace std;
void validate(float &num) {
while (num < 0 || num >= 1) {
cout << "\nEnter number in range of (0 - 1): ";
cin >> num;
}
}
const int SIZE = 10;
class Node {
public:
int data;
Node* next;
Node() : data(0), next(NULL) {}
Node(int data) {
this->data = data;
this->next = NULL;
}
};
class List {
private:
Node* head;
public:
List() {
this->head = NULL;
}
List(Node* head) {
this->head = head;
}
void insertion(int data)
{
Node *newNode = new Node(data);
if (head == NULL)
{
head = newNode;
}
else if (head->data >= newNode->data)
{
newNode->next = head;
head = newNode;
}
else
{
Node *traverse = head;
while (traverse->next != NULL && traverse->next->data < newNode->data)
{
traverse = traverse->next;
}
newNode->next = traverse->next;
traverse->next = newNode;
}
}
Node* getHead() {
return head;
}
};
int main()
{
float arr[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << "\nEnter value: ";
cin >> arr[i];
validate(arr[i]);
}
List list[SIZE];
for (int i = 0; i < SIZE; i++)
{
int index = floor(arr[i] * SIZE);
list[index].insertion(arr[i]);
}
int count = 0;
for (int i = 0; i < SIZE; i++)
{
if (list[i].getHead() == NULL)
{
continue;
}
Node *traverse = list[i].getHead();
while (traverse != NULL)
{
arr[count] = traverse->data;
traverse = traverse->next;
count++;
}
}
cout << "\nSorted List: ";
for (int i = 0; i < SIZE; i++)
{
cout << arr[i] << " ";
}
return 0;
}