Could you please write me Rust code that takes ownership of an array of integers and…
- User
Could you please write me Rust code that takes ownership of an array of integers and sorts them in ascending order?
- Assistant
Sure, here's an implementation in Rust:
codefn sort_ascending(arr: &mut [i32]) { arr.sort_unstable(); } fn main() { let mut arr = [5, 2, 4, 1, 3]; sort_ascending(&mut arr); println!("{:?}", arr); }This code sorts the array arr in place using the sort_unstable method. The sort_unstable method sorts the slice in place and may not preserve the order of equal elements.
- User
do it in descending order
- Assistant
Sure! To sort an array of integers in descending order, you can create a sort_descending function like this:
codefn sort_descending(arr: &mut [i32]) { arr.sort_unstable_by(|a, b| b.cmp(a)); } fn main() { let mut arr = [5, 2, 4, 1, 3]; sort_descending(&mut arr); println!("{:?}", arr); }Here, the
sort_unstable_bymethod is used with a comparison closure that reverses the ordering of elements. Thecmpmethod returns an ordering value that represents the relative order of two elements. Reversing the order of the arguments tocmpwill cause it to return a value that represents the opposite ordering, which is what we need for a descending sort.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)