forked from alexfertel/rust-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.rs
More file actions
31 lines (28 loc) · 759 Bytes
/
bubble_sort.rs
File metadata and controls
31 lines (28 loc) · 759 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// It sorts the array by repeatedly comparing the
// adjacent elements and swapping them if they are
// in the wrong order.
// Time complexity is O(N^2)
// Auxiliary space is O(1)
use super::traits::MutableSorter;
pub struct BubbleSort;
impl<T> MutableSorter<T> for BubbleSort {
fn sort(array: &mut [T])
where
T: Ord,
{
for i in 0..array.len() {
// Last i elements are already in place.
for j in 0..array.len() - 1 - i {
if array[j] > array[j + 1] {
array.swap(j, j + 1);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::super::traits::MutableSorter;
use super::BubbleSort;
sorting_tests!(BubbleSort::sort, inplace);
}