ページ

2011年4月12日火曜日

[C++] バブルソート書いてみた

このエントリーをはてなブックマークに追加



・2011年2月頃にC++で書いたバブルソート

#include <iostream>
#include <vector>
#include <ctime>

#define N 10

using namespace std;
typedef unsigned int size_t;

namespace sort{

//==============================================
// 交換関数
// argument :
// type : 交換したい数値01
// type : 交換したい数値02
//==============================================
template <class type> void swap(type * x, type * y){
type tmp = *x;
*x = *y;
*y = tmp;
}

/************************************************
/* バブルソートクラス
************************************************/
class CBubble{
public:
template <class type> void sort(type * X, bool flag){
for(size_t i = 0; i < X->size() - 1; i++){
for(size_t j = X->size() - 1; j > i; j--){
if(flag){
// 昇順
if(X->at(j - 1) > X->at(j)){
swap(&X->at(j - 1), &X->at(j));
}
}
else{
// 降順
if(X->at(j - 1) < X->at(j)){
swap(&X->at(j - 1), &X->at(j));
}
}
}
}
}
};

};

using namespace sort;


//===============================================
// main
//===============================================
int main(const int argc, char ** argv){

srand((size_t)time(NULL));


vector<float> X;

for(size_t i = 0; i < N; i++){
X.push_back((float)rand() / 3);
}

CBubble * objBubble = new CBubble;
objBubble->sort(&X, 1);

for(size_t i = 0; i < N; i++){
cout << X.at(i) << endl;
}

delete objBubble;

return 0;
}

0 件のコメント:

コメントを投稿