Skip to content

Commit bde20f5

Browse files
author
Floxyi
committed
Added a shaker sort algorithm in dart
1 parent 3b99adf commit bde20f5

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Diff for: sort/shaker_sort/dart/shaker_sort.dart

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
void main() {
2+
// define a list to be sorted
3+
final List<int> unsortedList = [10, 2, 8, 5, 6, 1, 4, 7, 9, 3];
4+
5+
// define expected result
6+
final List<int> expectedList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
7+
8+
// call the method and save sorted list
9+
final List<int> sortedList = shakerSort(unsortedList);
10+
11+
// test the resolution
12+
bool condition1 = sortedList.toSet().difference(expectedList.toSet()).isEmpty;
13+
bool condition2 = sortedList.length == expectedList.length;
14+
if (condition1 && condition2) {
15+
print('Successfully sorted the list!');
16+
}
17+
18+
// print the sorted list
19+
print(sortedList);
20+
}
21+
22+
// define a method that takes the list to sort as input
23+
List<int> shakerSort(List<int> list) {
24+
// the number of steps in the algorithm is only half the length of the input list
25+
for (int i = 0; i < list.length / 2; i++) {
26+
// first we go through every element in the list starting from the left
27+
for (int j = 0; j < list.length - 1; j++) {
28+
// if the next element is smaller than the current element, we need to swap them
29+
if (list[j] > list[j + 1]) {
30+
int temp = list[j];
31+
list[j] = list[j + 1];
32+
list[j + 1] = temp;
33+
}
34+
}
35+
36+
// now each element of the list is run through again from right to left
37+
for (int j = list.length - 1; j > 0; j--) {
38+
// if the next element is bigger than the current element, we need to swap them
39+
if (list[j] < list[j - 1]) {
40+
int temp = list[j];
41+
list[j] = list[j - 1];
42+
list[j - 1] = temp;
43+
}
44+
}
45+
}
46+
47+
return list;
48+
}

0 commit comments

Comments
 (0)