forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbubble_sort.dart
96 lines (90 loc) · 1.85 KB
/
bubble_sort.dart
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
import 'dart:io';
class BubbleSort
{
List<int> unsorted;
BubbleSort(this.unsorted);
//add array that you want to sort
void addArray(int count, List<int> list)
{
list = [];
unsorted = list;
for (int i = 0; i < count; i++)
{
print('Add number to array : ');
var input = stdin.readLineSync();
int x = int.parse(input);
assert(x is int);
unsorted.add(x);
}
}
printArray(List<int> array)
{
for (int i = 0; i < array.length; i++)
{
print(array[i]);
}
}
void sort(List<int> a)
{
for (var i = 0; i < a.length; i++)
{
bool swaped = false;
for (var j = i + 1; j < a.length; j++)
{
if (a[i] > a[j])
{
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
swaped = true;
}
}
if (!swaped) break;
}
}
}
void main()
{
List<int> unsorted = [];
BubbleSort bubbleSort = new BubbleSort(unsorted);
print('Enter the number of elements');
var countString = stdin.readLineSync();
int count = int.parse(countString);
bubbleSort.addArray(count, unsorted);
print('The given array is : ');
bubbleSort.printArray(bubbleSort.unsorted);
// sort the array and display using the next print
bubbleSort.sort(bubbleSort.unsorted);
print('Sorted Array is:');
bubbleSort.printArray(bubbleSort.unsorted);
}
/*Sample Input and Output
Enter the number of elements
6
Add number to array :
45
Add number to array :
78
Add number to array :
34
Add number to array :
21
Add number to array :
1
Add number to array :
98
The given array is :
45
78
34
21
1
98
Sorted Array is:
1
21
34
45
78
98
*/