2012年9月5日水曜日

開発環境

『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 10(章全部で復習), 10.3(練習問題)、辞書順ソートを解いてみる。

その他参考書籍

辞書順ソート

コード(TextWrangler)

sample.rb

#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

def dictionary_sort some_array
  recursive_sort some_array,[]
end

def recursive_sort unsorted_array,sorted_array
  return sorted_array if unsorted_array.length <= 0
  array = Array.new(unsorted_array)
  min = array.pop
  tmp = []
  array.each do |item|
    if item.upcase < min.upcase
      tmp.push min
      min = item
    else
      tmp.push item
    end
  end
  sorted_array.push min
  recursive_sort tmp, sorted_array
end

strings = %w[e a d b c E A D B C]
sorted_strings = dictionary_sort strings
puts "辞書順ソート前: #{strings.join(" ")}"
puts "辞書順ソート後: #{sorted_strings.join(" ")}"

入出力結果(Terminal)

$ ./sample.rb
辞書順ソート前: e a d b c E A D B C
辞書順ソート後: a A b B C c D d E e
$

0 コメント:

コメントを投稿