# バブルソート

### 概要

バブルソートの概要については。

バブルソート - Wikipedia

1コずつ数字をなめていって、数をデカいほうへよせていくイメージ。

### コード

```# -*- coding: utf-8 -*-
#/***********************************************************
#    bubsort.rb -- バブルソート
#***********************************************************/
def bubblesort( n, a )
k = n - 1
while (k >= 0)
j = -1
for i in 1..k
if (a[i - 1] > a[i])
j = i - 1
# ひとつ前の要素の数字が今の要素の数字より大きいなら
# 隣り合う数を入れ替える
x = a[j];  a[j] = a[i];  a[i] = x
end
end
p a
# 上のループが終了する時に終了させる
k = j
end
end

N = 20

a = []

printf("Before:")
for i in 0...N
a[i] = rand *100 + 1
printf(" %2d", a[i])
end
printf("\n")
printf "Enter Return"; gets
bubblesort(N, a)
printf("After: ")
for i in 0...N; printf(" %2d", a[i]); end
printf("\n")

exit 0
```

### 実行

```Before: 88 58 66  5 68 76 83  9 95 33  9 72 19 57 59 83  1 95 16 64
Enter Return
[58, 66, 5, 68, 76, 83, 9, 88, 33, 9, 72, 19, 57, 59, 83, 1, 95, 16, 64, 95]
[58, 5, 66, 68, 76, 9, 83, 33, 9, 72, 19, 57, 59, 83, 1, 88, 16, 64, 95, 95]
[5, 58, 66, 68, 9, 76, 33, 9, 72, 19, 57, 59, 83, 1, 83, 16, 64, 88, 95, 95]
[5, 58, 66, 9, 68, 33, 9, 72, 19, 57, 59, 76, 1, 83, 16, 64, 83, 88, 95, 95]
[5, 58, 9, 66, 33, 9, 68, 19, 57, 59, 72, 1, 76, 16, 64, 83, 83, 88, 95, 95]
[5, 9, 58, 33, 9, 66, 19, 57, 59, 68, 1, 72, 16, 64, 76, 83, 83, 88, 95, 95]
[5, 9, 33, 9, 58, 19, 57, 59, 66, 1, 68, 16, 64, 72, 76, 83, 83, 88, 95, 95]
[5, 9, 9, 33, 19, 57, 58, 59, 1, 66, 16, 64, 68, 72, 76, 83, 83, 88, 95, 95]
[5, 9, 9, 19, 33, 57, 58, 1, 59, 16, 64, 66, 68, 72, 76, 83, 83, 88, 95, 95]
[5, 9, 9, 19, 33, 57, 1, 58, 16, 59, 64, 66, 68, 72, 76, 83, 83, 88, 95, 95]
[5, 9, 9, 19, 33, 1, 57, 16, 58, 59, 64, 66, 68, 72, 76, 83, 83, 88, 95, 95]
[5, 9, 9, 19, 1, 33, 16, 57, 58, 59, 64, 66, 68, 72, 76, 83, 83, 88, 95, 95]
[5, 9, 9, 1, 19, 16, 33, 57, 58, 59, 64, 66, 68, 72, 76, 83, 83, 88, 95, 95]
[5, 9, 1, 9, 16, 19, 33, 57, 58, 59, 64, 66, 68, 72, 76, 83, 83, 88, 95, 95]
[5, 1, 9, 9, 16, 19, 33, 57, 58, 59, 64, 66, 68, 72, 76, 83, 83, 88, 95, 95]
[1, 5, 9, 9, 16, 19, 33, 57, 58, 59, 64, 66, 68, 72, 76, 83, 83, 88, 95, 95]
[1, 5, 9, 9, 16, 19, 33, 57, 58, 59, 64, 66, 68, 72, 76, 83, 83, 88, 95, 95]
After:   1  5  9  9 16 19 33 57 58 59 64 66 68 72 76 83 83 88 95 95```