Skip to main content

algorithmz/sorting/
bubble_sort.rs

1/// Returns the bubble sorted version of the input
2///
3/// This function takes a list as a reference and returns either the sorted list as a `Vec<i32>` or an error.
4///
5/// # Examples
6///
7/// Basic usage:
8/// ```
9/// let result = algorithmz::sorting::bubble_sort(&[2,1,4,3,5]).unwrap();
10/// assert_eq!(result, [1,2,3,4,5]);
11/// ```
12///
13/// With match statement:
14/// ```
15/// use algorithmz::sorting::bubble_sort;
16/// let my_list = [1,3,2,5,4];
17/// match bubble_sort(&my_list) {
18///     Err(e) => eprintln!("The error was: {}", e),
19///     Ok(nums) => println!("The result was: {:?}", nums),
20/// }
21/// ```
22pub fn bubble_sort(list: &[i32]) -> Result<Vec<i32>,String> {
23    if list.is_empty() {
24        return Err("The list cannot be empty!".to_string());
25    }
26    let mut result =  list.to_vec();
27    let length = result.len();
28    for i in 0..length {
29        let mut swapped = false;
30        for j in 0..(length - 1 - i) {
31            if result[j] > result[j+1] {
32                result.swap(j,j+1);
33                swapped = true;
34            }
35        }
36        if !swapped {
37            break;
38        }
39    }  
40    Ok(result)
41}
42