tinystd/sort/bubble.rs
1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5// http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12//! [Bubblesort][1]. Not good.
13//! [1]: https://en.wikipedia.org/wiki/Bubble_sort
14use super::*;
15
16pub struct Bubble;
17impl Sorter for Bubble {
18 fn sort<T>(&self, slice: &mut [T])
19 where
20 T: Ord,
21 {
22 let mut swapped = true;
23 while swapped {
24 swapped = false;
25 for i in 1..slice.len() {
26 if slice[i - 1] > slice[i] {
27 slice.swap(i, i - 1);
28 swapped = true;
29 }
30 }
31 }
32 }
33}
34#[cfg(test)]
35mod tests {
36 use super::*;
37
38 #[test]
39 fn it_works() {
40 let mut items = vec![4, 2, 3, 1];
41 Bubble.sort(&mut items);
42 assert_eq!(items, &[1, 2, 3, 4]);
43 }
44}