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?

More than 1 year has passed since last update.

基本情報対策:科目B「バブルソート」

Posted at

バブルソートとは

隣接する値どうしの比較、入れ替えを繰り返すことで
値を大きい順または小さい順に整列させる方法。

主に以下のような状況で使用(Chat-GTP回答)

学習と教育目的: バブルソートは非常にシンプルなアルゴリズムであり、ソートの基本的な考え方を理解するための教育的な目的で使われます。アルゴリズムとしての基本的な動作原理を理解するために、初心者にとっては有用な例となります。

小規模なデータセット:
データセットの要素数が少なく、性能の最適化が重要でない場合に、バブルソートが使用されることがあります。シンプルな実装が容易であるため、簡単なソート処理に適しています。

一方で、バブルソートは大規模なデータセットには適していません。その理由は、バブルソートの時間計算量がO(n^2)であるため、要素数が多くなると処理にかかる時間が急激に増加してしまうからです。そのため、効率的なソートアルゴリズム(例:クイックソートやマージソートなど)を使用することが一般的です。

バブルソートは実用的なソートアルゴリズムとしてはあまり使われないものの、教育や学習の目的で理解する価値はあります。アルゴリズムとしての基本的な概念を理解し、他のソートアルゴリズムとの比較を通じてその効率性や利点を学ぶことが重要です。

ソースコード

Main.java

import java.util.Arrays;

public class Main {
    public static int[] bubbleSortMachine(int[] array){
        int tmp;
        int length = array.length;

//  外側のループは要素を1つずつ減少させていく
        for(int i=0; i<length-1; i++){
            for(int j = length-1; i<j; j-- ){
                //前後の要素の比較を行い入れ替えるシンプルな構造
                if(array[j]<array[j-1]){ 
                    tmp = array[j-1];
                    array[j-1] = array[j];
                    array[j] = tmp;
                }
            }
        }
        System.out.println(Arrays.toString(array));
        return array;
    }
}

MainTest.java

import org.junit.Test;


import static org.junit.Assert.assertArrayEquals;

public class MainTest {
    @Test
    public void testBubbleSortMachineForArray() {
        // テスト用のデータ
        int[] array = {10,9,8,7,6,5,4,3,2,1,0};

        // 期待される結果
        int[] expected ={0,1,2,3,4,5,6,7,8,9,10};

        // テスト対象のメソッドを実行
        int[] sortedArray = Main.bubbleSortMachine(array);

        // 期待される結果と実際の結果を比較
        assertArrayEquals(expected, sortedArray);
    }
}
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?