Skip to content

Commit 4e3bb48

Browse files
Penzsparal
authored andcommitted
Added Rust implementation of bubble sort. (algorithm-archivists#136)
* Added Rust implementation of bubble sort. * Fixed tiny spelling mistake. * Changed sort parameter. * Changed a comment. * Removed comment.
1 parent bd04b7e commit 4e3bb48

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

CONTRIBUTORS.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,5 @@ Gathros
55
Jeremie Gillet (- Jie -)
66
Salim Khatib
77
Hitesh C
8-
Jess 3Jane
8+
Pen Pal
9+
Jess 3Jane

chapters/sorting_searching/bubble/bubble_sort.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ This means that we need to go through the vector $$\mathcal{O}(n^2)$$ times with
2020
[import, lang:"haskell"](code/haskell/bubbleSort.hs)
2121
{% sample lang="cpp" %}
2222
[import, lang:"c_cpp"](code/c++/bubblesort.cpp)
23+
{% sample lang="rs" %}
24+
[import:6-19, lang:"rust"](code/rust/bubble_sort.rs)
2325
{% sample lang="d" %}
2426
[import:3-18, lang:"d"](code/d/bubble_sort.d)
2527
{% endmethod %}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
extern crate rand; // External crate that provides random number generation tools
2+
3+
use rand::{thread_rng, Rng}; // Used for random number generation
4+
use rand::distributions::Uniform; // Used for a uniform distribution
5+
6+
fn bubble_sort(a: &mut [u32]) {
7+
let n = a.len();
8+
9+
for _ in 0..n {
10+
for j in 1..n {
11+
if a[j - 1] > a[j] {
12+
a.swap(j, j - 1);
13+
}
14+
}
15+
}
16+
}
17+
18+
fn main() {
19+
let mut rng = thread_rng(); // Create random number generator
20+
let num_range = Uniform::new_inclusive(0, 10000); // Obtain uniform distribution of range [0, 10000]
21+
let mut rand_vec: Vec<u32> = rng.sample_iter(&num_range).take(10).collect();
22+
// Generates random values over that range, take 10 values from it and collect in vector
23+
24+
println!("Before sorting: {:?}", rand_vec);
25+
bubble_sort(&mut rand_vec);
26+
println!("After sorting: {:?}", rand_vec);
27+
}

0 commit comments

Comments
 (0)