0
1

More than 3 years have passed since last update.

pythonでバブルソート作ってみた

Last updated at Posted at 2021-07-16

背景

知り合いから、pythonの課題が解けないと言われた。
python全く書いたことない(普段はruby)けど、いけるやろうと思って、タイムアタック的な感じでやってみた。

所要時間

1時間くらい。
なんだかんだ文法を調べるのに時間がかかった印象。

できたソースコード

sample.py
list = [4,6,1,2,8]
is_required_to_sort = True
max_compare_count = len(list) - 1

while is_required_to_sort:
    sort_count = 0
    for i in range(max_compare_count):
        if list[i] < list[i + 1]:
            q = list[i]
            list[i] = list[i + 1]
            list[i + 1] = q
            sort_count += 1

    if sort_count == 0:
        is_required_to_sort = False

print(list)
実行結果
[8, 6, 4, 2, 1]

改善版

@StrawBerryMoon さんありがとうございます。

sample.py
is_required_to_sort = True
max_compare_count = len(lst) - 1

while is_required_to_sort:
    is_required_to_sort = False
    for i in range(max_compare_count):
        if lst[i] < lst[i + 1]:
            lst[i], lst[i + 1] = lst[i + 1], lst[i]
            is_required_to_sort = True

あとがき

  • アルゴリズム的な問題を解くコードは普段書かないので、勉強になった
  • 実行結果は手元で試した限りはあってるが、このコードは本当に正しいのだろうか
  • アルゴリズムのコードは、変数がわかりにくすぎるものが多い(まあ、わかりやすくする必要もないだろうが)ので、少しわかりやすくなるよう意識はしてみた
  • sort_countはis_sortedにして、真偽値を入れてもいいかもしれない
0
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1