Write a bubble sort in Rust
- User
Write a bubble sort in Rust
- Assistant
Sure! Here's an implementation of the bubble sort algorithm in Rust:
fn bubble_sort(arr: &mut [i32]) { let n = arr.len(); for i in 0..n { for j in 0..n-i-1 { if arr[j] > arr[j+1] { arr.swap(j, j+1); } } } }This function takes a mutable reference to an array of
i32integers and sorts it in ascending order using the bubble sort algorithm.The outer loop iterates over the array
ntimes, wherenis the length of the array. The inner loop iterates over the unsorted portion of the array, which decreases by one with each iteration of the outer loop.Inside the inner loop, we compare adjacent elements of the array and swap them if they are in the wrong order. The
swapmethod is called on the mutable reference to the array, which swaps the values at the given indices.After the function completes, the array will be sorted in ascending order.
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)