ボゾソート

アバター
a5ua
記事: 199
登録日時: 14年前

ボゾソート

投稿記事 by a5ua » 14年前

「ソート済みでなければ、ランダムに2要素を入れ替える」
を繰り返す。非常に効率悪

CODE:

#include 
#include 
#include 
#include 

namespace a5ua
{
	// 0 ~ n - 1 の整数乱数
	int random(int n)
	{
		return static_cast(std::rand() / static_cast(RAND_MAX + 1) * n);
	}

	// 昇順にソート済みかどうか判定
	template 
	bool is_sorted(InIt first, InIt last)
	{
		if (first == last) {
			return true;
		}

		InIt next = first;

		for (++next ; next != last; ++first, ++next) {
			if (!(*first 
	void bozo_sort(InIt first, InIt last)
	{
		const int n = std::distance(first, last);

		while (!is_sorted(first, last)) {
			InIt i = first;
			InIt j = first;
			std::advance(i, random(n));
			std::advance(j, random(n));
			std::swap(*i, *j);
		}
	}
}

#include 
#include 
#include 
#include 

int main()
{
	std::srand(static_cast(std::time(0)));

	std::vector v(5);
	std::generate(v.begin(), v.end(), &std::rand);

	std::copy(v.begin(), v.end(), std::ostream_iterator(std::cout, " "));
	std::cout (std::cout, " "));
	std::cout << "\n";

	return 0;
}
(追記)
・乱数の発生確率が一様になっていないのを修正
・同じ数があると一生終わらないので、比較を<=に変更
最後に編集したユーザー a5ua on 2010年10月18日(月) 00:50 [ 編集 1 回目 ]

アバター
あーる@Reputeless
記事: 84
登録日時: 14年前

Re: ボゾソート

投稿記事 by あーる@Reputeless » 14年前

20個あたりになると、もう太刀打ちできませぬ (´;ω;
朝までには終わってるかな...

アバター
tana
記事: 33
登録日時: 14年前

Re: ボゾソート

投稿記事 by tana » 14年前

お初です。
気になったんで拝見させていただきました。
平均計算量がO(n*n!)、最悪計算量がO(∞)なんてソートがあったんですねww
実に面白いですw