バブルソートの変形になるの?
- 先頭から隣り合うデータを比較
- 大小が逆ならスワップ
- スワップした時は一つ前に戻ってまた比較
- これを繰り返す
1 #!/usr/local/bin/ruby
2 # encoding: utf-8
3 class Array
4 def thought
5 n = 0
6 until n == self.length - 1
7 if comp(n)
8 swap(n)
9 n -= 1 unless n < 0
10 redo unless n < 0
11 end
12 n += 1
13 end
14 self
15 end
16
17 private
18 def comp(n)
19 self[n] > self[n+1]
20 end
21
22 def swap(n)
23 self[n], self[n+1] = self[n+1], self[n]
24 end
25 end
26
27 a = [4,3,6,8,1,2,9,5,7,0,12,23,87,13,33,14,56,21,89,100,44,22]
28 p a.thought
No comments:
Post a Comment