Created
February 11, 2025 14:24
-
-
Save xiabingquan/2bc415a0e2239df58fb999d77c8e3de5 to your computer and use it in GitHub Desktop.
A minimal example of bubble sort in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use rand::Rng; | |
fn bubble_sort<T: Ord>(arr: &mut [T]) { | |
let n = arr.len(); | |
for i in 0..n { | |
for j in 0..n-1-i { | |
if arr[j] > arr[j + 1] { | |
arr.swap(j, j + 1); | |
} | |
} | |
} | |
} | |
fn main() { | |
let mut rng = rand::thread_rng(); | |
let n: u32 = rng.gen_range(10..100); | |
let mut arr = vec![0; n as usize]; | |
for i in 0..arr.len() { | |
arr[i] = rng.gen_range(0..100); | |
} | |
println!("Before sorting: {:?}", arr); | |
bubble_sort(&mut arr); | |
println!("After sorting: {:?}", arr); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment