Skip to content

Instantly share code, notes, and snippets.

@nebelgrau77
Last active July 18, 2020 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nebelgrau77/81c8f09dee7bcbeda6aafc7a1e742f4a to your computer and use it in GitHub Desktop.
Save nebelgrau77/81c8f09dee7bcbeda6aafc7a1e742f4a to your computer and use it in GitHub Desktop.
bubble sort algorithm

bubble sort algorithm

https://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Bubble_sort

Implemented for generic types, as long as they implement Copy and PartialOrd traits.

fn main () {
    
    // example1: numbers 

    let mut arr1 = [2,5,3,7,1,4,5,6,7,6];    
    let sorted_arr1 = bubblesort(&mut arr1);
    for item in sorted_arr1.iter() {
        println!("{}", item);
    }
   
    // example 2: strings

    let mut arr2 = ["cat", "bat", "rat", "hat"];    
    let sorted_arr2 = bubblesort(&mut arr2);
    for item in sorted_arr2.iter() {
        println!("{}", item);
    }    
}



fn bubblesort<T: std::marker::Copy + std::cmp::PartialOrd>(arr: &mut [T]) -> &[T] {

    let mut temp: T;                        // temporary storage for swapping values

    for i in 0..arr.len() {
        for j in i..arr.len() {            
            if arr[i] > arr[j] {                
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;                
            }        
        }        
    } 
    arr                                     // return the sorted array
}
```rust
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment