fork download
  1. pub fn bubble_sort<T: Ord>(arr: &mut [T]) {
  2. // Iterate through the array, reducing the search range each pass
  3. for i in 0..arr.len() {
  4. let mut swapped = false;
  5.  
  6. // Last i elements are already sorted, skip them
  7. for j in 0..(arr.len() - i - 1) {
  8. // Compare adjacent elements and swap if needed
  9. if arr[j] > arr[j + 1] {
  10. arr.swap(j, j + 1);
  11. swapped = true;
  12. }
  13. }
  14.  
  15. // Early exit if no swaps occurred - array is sorted
  16. if !swapped {
  17. break;
  18. }
  19. }
  20. }
  21.  
  22. fn main() {
  23. let mut numbers = [5, 2, 9, 1, 5, 6];
  24. println!("Before: {:?}", numbers);
  25.  
  26. bubble_sort(&mut numbers);
  27. println!("After: {:?}", numbers);
  28. }
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
Before: [5, 2, 9, 1, 5, 6]
After:  [1, 2, 5, 5, 6, 9]