add dart examples for chapter 1 and 2 (#209)
* add dart example for chapter 1 * add dart example for chapter 2
This commit is contained in:
25
01_introduction_to_algorithms/dart/binary_search.dart
Normal file
25
01_introduction_to_algorithms/dart/binary_search.dart
Normal file
@@ -0,0 +1,25 @@
|
||||
void main() {
|
||||
final myList = [1, 3, 5, 7, 9];
|
||||
print(binarySearch(myList, 3));
|
||||
print(binarySearch(myList, -1));
|
||||
}
|
||||
|
||||
int? binarySearch(List<int> list, int item) {
|
||||
int low = 0;
|
||||
int high = list.length - 1;
|
||||
|
||||
while (low <= high) {
|
||||
final mid = (low + high) ~/ 2;
|
||||
final guess = list[mid];
|
||||
|
||||
if (guess == item) {
|
||||
return mid;
|
||||
}
|
||||
|
||||
if (guess > item) {
|
||||
high = mid - 1;
|
||||
} else {
|
||||
low = mid + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
29
02_selection_sort/dart/selection_sort.dart
Normal file
29
02_selection_sort/dart/selection_sort.dart
Normal file
@@ -0,0 +1,29 @@
|
||||
main() {
|
||||
print(selectionSort([5, 3, 6, 2, 10]));
|
||||
}
|
||||
|
||||
List<int> selectionSort(List<int> arr) {
|
||||
final List<int> newArr = List.empty(growable: true);
|
||||
final arrLength = arr.length;
|
||||
|
||||
for (int i = 0; i < arrLength; i++) {
|
||||
final smallest = findSmallest(arr);
|
||||
newArr.add(arr.removeAt(smallest));
|
||||
}
|
||||
|
||||
return newArr;
|
||||
}
|
||||
|
||||
int findSmallest(List<int> arr) {
|
||||
int smallest = arr[0];
|
||||
int smallestIndex = 0;
|
||||
|
||||
for (int i = 1; i < arr.length; i++) {
|
||||
if (arr[i] < smallest) {
|
||||
smallest = arr[i];
|
||||
smallestIndex = i;
|
||||
}
|
||||
}
|
||||
|
||||
return smallestIndex;
|
||||
}
|
||||
Reference in New Issue
Block a user