Skip to content

Commit b3a143a

Browse files
authored
add dart examples for chapter 1 and 2 (egonSchiele#209)
* add dart example for chapter 1 * add dart example for chapter 2
1 parent cd38dc1 commit b3a143a

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
void main() {
2+
final myList = [1, 3, 5, 7, 9];
3+
print(binarySearch(myList, 3));
4+
print(binarySearch(myList, -1));
5+
}
6+
7+
int? binarySearch(List<int> list, int item) {
8+
int low = 0;
9+
int high = list.length - 1;
10+
11+
while (low <= high) {
12+
final mid = (low + high) ~/ 2;
13+
final guess = list[mid];
14+
15+
if (guess == item) {
16+
return mid;
17+
}
18+
19+
if (guess > item) {
20+
high = mid - 1;
21+
} else {
22+
low = mid + 1;
23+
}
24+
}
25+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
main() {
2+
print(selectionSort([5, 3, 6, 2, 10]));
3+
}
4+
5+
List<int> selectionSort(List<int> arr) {
6+
final List<int> newArr = List.empty(growable: true);
7+
final arrLength = arr.length;
8+
9+
for (int i = 0; i < arrLength; i++) {
10+
final smallest = findSmallest(arr);
11+
newArr.add(arr.removeAt(smallest));
12+
}
13+
14+
return newArr;
15+
}
16+
17+
int findSmallest(List<int> arr) {
18+
int smallest = arr[0];
19+
int smallestIndex = 0;
20+
21+
for (int i = 1; i < arr.length; i++) {
22+
if (arr[i] < smallest) {
23+
smallest = arr[i];
24+
smallestIndex = i;
25+
}
26+
}
27+
28+
return smallestIndex;
29+
}

0 commit comments

Comments
 (0)