---
title: "Bubble排序的ruby实现"
author: "Goldice"
date: "2015-07-31T09:39:26Z"
tags: []
categories: ["编程语言"]
slug: "bubble-ruby"
draft: false
lastmod: "2015-07-31T09:39:26Z"
id: 2231808
url: "https://jdoc.iteye.com/blog/2231808"
---

```
list = [2, 5,  18, 8, 29, 10, 2, 9]


puts "before reorder: #{list.join(',')}"

def swap(list, i, j)
  tmp = list[i]
  list[i] = list[j]
  list[j] = tmp
end

list.each_with_index do |_, index|
  next if index == 0
  (index-1).downto(0).each do |j|
    if(list[j+1] > list[j])
      swap(list, j+1, j)
    else
      break
    end
  end
end

puts "after reorder: #{list.join(',')}"
```