2012年9月6日木曜日

開発環境

『初めてのプログラミング 第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
  tmp_sort some_array,[]
end

def tmp_sort unsorted_array,sorted_array
  array = Array.new(unsorted_array)
  while array.length > 0
    min = array.pop
    tmp = []
    array.each do |item|
      if item.downcase < min.downcase
        tmp.push min
        min = item
      else
        tmp.push item
      end
    end
    sorted_array.push min
    array = tmp
  end
  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 コメント:

コメントを投稿