Skip to content

Commit

Permalink
Merge pull request ZoranPandovski#1056 from NotThatBowser/add-dart-bu…
Browse files Browse the repository at this point in the history
…bblesort

Add Dart implementation of Bubble Sort
  • Loading branch information
ZoranPandovski authored Oct 2, 2018
2 parents c1b2399 + ee7f833 commit b12faa1
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions sort/bubble_sort/dart/bubble_sort.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/// Bubble Sort the input list then return it.
List<int> bubbleSort(List<int> items) {
bool isSorted = false;

while (!isSorted) {
// We know the list isn't sorted whenever we have to do a swap.
isSorted = true;

for (var i = 0; i < items.length - 1; i++) {
if (items[i] > items[i + 1]) {
isSorted = false;
final int higherElementCopy = items[i];
items[i] = items[i + 1];
items[i + 1] = higherElementCopy;
}
}
}

return items;
}

// ----- Test -----
void main() {
// 1. Arrange
final List<int> unsortedInput = [10, 2, 8, 5, 6, 1, 4, 7, 9, 3];
final List<int> expectedOutput = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// 2. Act
final List<int> sortedOutput = bubbleSort(unsortedInput);
print(sortedOutput);

// 3. Assert
// No simple list equality in dart yet so using 'fold' to recursively check
// each sorted element compared to the expected output at each index.
int i = 0;
final bool isEqual = sortedOutput.fold(
true,
(result, item) => result && item == expectedOutput[i++],
);
print(isEqual);
}

0 comments on commit b12faa1

Please sign in to comment.