cleanCode(2)

#include<iostream>
#include<cstdio>
#include<vector>
#include<string>
#include<algorithm>

using namespace std;
const int MAX_SIZE = 10;

class BubbleIntArray
{
public:
	BubbleIntArray() {}
	BubbleIntArray(vector<int> a) {
		intArray = a;
		sorted = false;
	}
	~BubbleIntArray(){}

	int size() {
		return intArray.size();
	}

	int at(int i) {
		return intArray.at(i);
	}

	void bubbleSwap(int i, int j) {
		int temp = intArray.at(i);
		intArray.at(i) = intArray.at(j);
		intArray.at(j) = temp;
	}

	bool isSorted() {
		return sorted;
	}

	void setSorted() {
		sorted = true;
	}

	void showBubbleArrayInfo() {
		for (int i : intArray) {
			cout << i << " ";
		}
		cout << endl;
	}
private:
	vector<int> intArray;
	bool sorted;
};

//相关的函数放到一起,函数只做一件事
//多个参数定义为类,做到一个输入一个输出
void bubbleOneLine(BubbleIntArray &a) {
	bool hasUpdate = false;
	for (int j = 0; j + 1 < a.size(); j++) {
		if (a.at(j) > a.at(j + 1))
		{
			a.bubbleSwap(j, j + 1);
			hasUpdate = true;
		}
	}
	if (!hasUpdate) a.setSorted();
}

//没有返回值最好,对输入参数的转换,转换的结果应该体现在返回值上
void bubbleSort(BubbleIntArray &a) {
	for (int i = 0; i < a.size(); i++) {
		if(!a.isSorted())
		bubbleOneLine(a);
	}
	a.setSorted();//如果要修改参数的某种状态,就修改所属对象的的状态(面向对象)
}


int main() {
	vector<int> a;
	for (int i = 0; i <= 4; i++) {
		a.push_back(i);
		a.push_back(4-i);
	}

	BubbleIntArray testBubble(a);
	bubbleSort(testBubble);
	testBubble.showBubbleArrayInfo();

	system("pause");
	return 0;
}
发布了27 篇原创文章 · 获赞 1 · 访问量 1425

猜你喜欢

转载自blog.csdn.net/qq_34890856/article/details/103985881
2
>&2
α2
2-2
今日推荐