c++ 冒泡排序

#include <iostream>
using namespace std;


class maopao  //類
{
private:
	int chang;//長
	int *arr;//數組
	int t;//交換數據會用到
	void small_to_big(int *aa, int c);//從小到大排序
	void big_to_small(int *aa, int c);//從大到小排序
	void swap(int &a, int &b);//交換
public:
	maopao(int *aa, int c);//構造函數
	~maopao();//析構函數
	void show();//外部調用接口
	void small_to_big();
	void big_to_small();
};

//構造函數
maopao::maopao(int *aa, int c)
{
	arr = aa;//輸入數組賦給arr
	chang = c;//輸入長度賦給chang
}
//析構函數
maopao::~maopao()
{
	cout << "結束" << endl;
}
//顯示數組
void maopao::show()
{
	for (int i = 0; i < chang; i++)
	{
		cout << arr[i] << " ";
	}
	cout << endl;
}

//從小到大
void maopao::small_to_big()
{
	small_to_big(arr, chang);
}

void maopao::small_to_big(int *aa, int c)
{
	for (int i = 0; i < c; i++)
	{
		for (int j = 0; j < c - i - 1; j++)
		{
			if (aa[j] > aa[j + 1])
			{
				swap(aa[j], aa[j + 1]);
			}
		}
	}
}

//從大到小
void maopao::big_to_small()
{
	big_to_small(arr, chang);
}
void maopao::big_to_small(int *aa, int c)
{
	for (int i = 9; i > 0; i--)
	{
		for (int j = 9; j > c - i - 1; j--)
		{
			if (aa[j] > aa[j - 1])
			{
				swap(aa[j], aa[j - 1]);
			}
		}
	}
}
//交換
void maopao::swap(int &a, int &b)
{
	t = a;
	a = b;
	b = t;
}




int main(int argc, char *args[])
{
	int buf[10] = { 12, 4, 34, 6, 8, 65, 3, 2, 988, 45 };
	int m = sizeof(buf) / sizeof(int);//申請內存空間,並得知數組長度
	maopao sa1(buf, m);

	cout << "排序前:" << endl;
	sa1.show();

	sa1.small_to_big();
	cout << "從小到大排序後:" << endl;
	sa1.show();

	sa1.big_to_small();
	cout << "從大到小排序後:" << endl;
	sa1.show();
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章