Skip to content

Commit bf9bd60

Browse files
authored
fix: bubble_sort failed when vec is empty (rust-lang#348)
1 parent 900a0e6 commit bf9bd60

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

src/sorting/bubble_sort.rs

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
pub fn bubble_sort<T: Ord>(arr: &mut [T]) {
2+
if arr.is_empty() {
3+
return;
4+
}
25
let mut sorted = false;
36
let mut n = arr.len();
47
while !sorted {
@@ -15,25 +18,28 @@ pub fn bubble_sort<T: Ord>(arr: &mut [T]) {
1518

1619
#[cfg(test)]
1720
mod tests {
21+
use super::super::is_sorted;
1822
use super::*;
1923

2024
#[test]
2125
fn descending() {
2226
//descending
2327
let mut ve1 = vec![6, 5, 4, 3, 2, 1];
2428
bubble_sort(&mut ve1);
25-
for i in 0..ve1.len() - 1 {
26-
assert!(ve1[i] <= ve1[i + 1]);
27-
}
29+
assert!(is_sorted(&ve1));
2830
}
2931

3032
#[test]
3133
fn ascending() {
3234
//pre-sorted
3335
let mut ve2 = vec![1, 2, 3, 4, 5, 6];
3436
bubble_sort(&mut ve2);
35-
for i in 0..ve2.len() - 1 {
36-
assert!(ve2[i] <= ve2[i + 1]);
37-
}
37+
assert!(is_sorted(&ve2));
38+
}
39+
#[test]
40+
fn empty() {
41+
let mut ve3: Vec<usize> = vec![];
42+
bubble_sort(&mut ve3);
43+
assert!(is_sorted(&ve3));
3844
}
3945
}

0 commit comments

Comments
 (0)