Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ Gathros
Jeremie Gillet (- Jie -)
Salim Khatib
Hitesh C
Pen Pal
2 changes: 2 additions & 0 deletions chapters/sorting_searching/bubble/bubble_sort.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ This means that we need to go through the vector $$\mathcal{O}(n^2)$$ times with
[import, lang:"haskell"](code/haskell/bubbleSort.hs)
{% sample lang="cpp" %}
[import, lang:"c_cpp"](code/c++/bubblesort.cpp)
{% sample lang="rs" %}
[import:6-19, lang:"rust"](code/rust/bubble_sort.rs)
{% endmethod %}

... And that's it for the simplest bubble sort method.
Expand Down
30 changes: 30 additions & 0 deletions chapters/sorting_searching/bubble/code/rust/bubble_sort.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
extern crate rand; // External crate that provides random number generation tools

use rand::{thread_rng, Rng}; // Used for random number generation
use rand::distributions::Uniform; // Used for a uniform distribution

fn bubble_sort(a: &mut Vec<u32>) {
Copy link
Contributor

@zsparal zsparal Jun 28, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should take &mut [u32] since it doesn't use any functionality on Vec, and taking slices is strictly more general (for example it could allow you to partially sort a vector).

let n = a.len();

for _ in 0..n {
for j in 1..n {
if a[j - 1] > a[j] {
// Swaps values at indices j - 1 and j
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rust has a swap method on slices, I would use that instead of the explicit swap written here. It's faster and it's more descriptive

let temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
}
}
}
}

fn main() {
let mut rng = thread_rng(); // Create random number generator
let num_range = Uniform::new_inclusive(0, 10000); // Obtain uniform distribution of range [0, 10000]
let mut rand_vec: Vec<u32> = rng.sample_iter(&num_range).take(10).collect();
// Generates random values over that range, take 10 values from it and collect in vector

println!("Before sorting: {:?}", rand_vec);
bubble_sort(&mut rand_vec);
println!("After sorting: {:?}", rand_vec);
}