Skip to content

Commit 521f5f3

Browse files
authored
Improve Bubble Sort with sorted flag (rust-lang#308)
1 parent bbc60e4 commit 521f5f3

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

src/sorting/bubble_sort.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
pub fn bubble_sort<T: Ord>(arr: &mut [T]) {
2-
for i in 0..arr.len() {
3-
for j in 0..arr.len() - 1 - i {
4-
if arr[j] > arr[j + 1] {
5-
arr.swap(j, j + 1);
2+
let mut sorted = false;
3+
let mut n = arr.len();
4+
while !sorted {
5+
sorted = true;
6+
for i in 0..n - 1 {
7+
if arr[i] > arr[i + 1] {
8+
arr.swap(i, i + 1);
9+
sorted = false;
610
}
711
}
12+
n -= 1;
813
}
914
}
1015

0 commit comments

Comments
 (0)