Scratchでリスト内の数字を並べ替える(バブルソート)方法を紹介します。
完成動作
https://scratch.mit.edu/projects/517109718/

完成コード


解説
前提
・以下の2つの変数を作成し、チェックを外す。

・以下のリストを作成

解説
リストに数値をランダムに追加機能
・スプライト1(リストに数値をランダムに追加)が押されたら”数字のリスト”内をすべて削除する。

・”数字のリスト”に1から50までの乱数を5個追加する。

並べ替え機能
・スプライト2(並べ替え)が押されたら”数字のリスト長さ-1回”繰り返す。(以下に説明することをリストの長さ分繰り返す)

・”番号”に”数字のリストの長さ”にする。

・「”数字のリスト”内の一番下から順に隣り合う数字を比較して、下にある数字よりも上にある数字の方が大きければ、入れ替える。(これによって、一番小さい数字が一番上に行く。)」ということをリストの一番上になるまで繰り返すことによって、上から順に小さい数が並ぶようになる。

コメント