0
1

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.

バブルソート

Posted at

はじめに

前回は挿入ソートを振り返ったので、次はバブルソート。

バブルソートとは

隣り合う数字の並び順が逆になっている要素がなくなるまで、以下の処理を繰り返すソート手法。

  1. 配列の末尾から順に隣接する要素の大小を確認
  2. 大小関係が逆ならば要素の入れ替え(交換)をする

具体例

image.png

計算量

image.png

image.png

ソースコード

数字配列を受け取って、並び替えて返す関数を作成。

vector<long> bubbleSort(vector<long> v)
{
	long n = v.size();
	for (long i = 0; i < n - 1; i++) // 確定した数字の数
	{
		for (long j = n - 1; j >= i + 1; j--) // 比較を行う範囲
		{
			if (v[j - 1] > v[j])
			{
				long tmp = v[j];
				v[j] = v[j - 1];
				v[j - 1] = tmp;
			}
		}
	}

	return v;
}

前回記事

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?