0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

バブルソートを行う

Posted at

配列の中の数字を小さい数順に並び替えたい時などは、バブルソートを行う

(例)
配列:100, 0, 15, 22, 69, 985, 47

public class Exercise {
    public void run(){
        int[] array = new int[] {100, 0, 15, 22, 69, 985, 47};

        // forを使って隣同士の数を比較し、必要に応じて入れ替える
        for(int i = 0; i <= array.length - 1 - 1; i++) {
            for(int j = array.length - 1; j >= i + 1; j--) {
                if(array[j] < array[j - 1]){
                    // tempで一時置き場を作ってarray[j]を一旦置いておく
                    int temp = array[j];
                    // array[j]があったところにarray[j - 1]を置く
                    array[j] = array[j - 1];
                    // array[j - 1]があったところにtempにあるもの(array[j])を置く
                    array[j - 1] = temp;
                }
            }
        }

        // forを使って並び替え後のarrayの値を1つずつ出力する
        for(int i = 0; i <= array.length - 1; i++){
            System.out.println(array[i]);
        }
    }
}

結果

0
15
22
47
69
100
985
0
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?