Created
June 1, 2019 22:14
-
-
Save rust-play/a6c82095ed8d3f8d167cbfa62eb79a12 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains 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
fn main() { | |
let mut arr = [12, 8, 10, 3, 5, 10, 45]; | |
if let Some(elem) = arr.get(10) { | |
println!("Element requested: {}.", elem); | |
} else { | |
println!( | |
"Element at index {} could not be found in an array of size {}.", | |
10, | |
arr.len() | |
); | |
} | |
print_bars(&arr); | |
bubble_it(&mut arr); | |
print_bars(&arr); | |
} | |
// Print a bar chart with a given array | |
fn print_bars(arr: &[isize]) { | |
for val in arr.iter() { | |
print!("{:3}: ", val); | |
for _i in 0..*val { | |
print!("•"); | |
} | |
println!(""); | |
} | |
println!(""); | |
} | |
/// Bubble sorting algorithm | |
fn bubble_it(arr: &mut [isize]) { | |
for i in 0..(arr.len() - 1) { | |
let mut swaps = 0; | |
for j in 0..(arr.len() - i - 1) { | |
if arr[j] > arr[j + 1] { | |
let temp = arr[j]; | |
arr[j] = arr[j + 1]; | |
arr[j + 1] = temp; | |
swaps += 1; | |
} | |
} | |
if swaps == 0 { | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment