算法思想:不断比较 不断交换
全部代码
#include <iostream>
#include <vector>
int init_array(std::vector<int>*);
int swap_xn(std::vector<int>*, int, int);
int bubble_sort(std::vector<int>*);
int main()
{
std::vector<int> array;
init_array(&array);
bubble_sort(&array);
for (int i = 0; i < array.size(); ++i)
{
std::cout << "冒泡后的元素排列顺序为:" << array[i] << std::endl;
}
return 0;
}
int init_array(std::vector<int> *array)
{
for (int i = 9; i >= 0; --i)
{
(*array).push_back(i);
}
return 0;
}
int bubble_sort(std::vector<int> *array)
{
bool flag = true;
for (int i = 0; i < (*array).size() && flag; ++i)
{
flag = false;
for (int j = (*array).size() - 2; j >= i; --j)
{
if ((*array)[j] > (*array)[j+1])
{
swap_xn(array, j, j+1);
flag = true;
}
}
}
return 0;
}
int swap_xn(std::vector<int> *array, int front, int next)
{
int temp = (*array)[front];
(*array)[front] = (*array)[next];
(*array)[next] = temp;
return 0;
}