冒泡排序
1. 动态演示:
解法一:
#include<iostream>
#include<algorithm>
using namespace std;
void BubbleSort(int arr[], int n)
{
bool exchange;
for (int i = 0; i < n - 1; ++i) 外层循环控制趟数,总趟数为n-1
{
exchange = false;
for (int j = 0; j < n - 1 - i; ++j) //内层循环为当前i趟数 所需要比较的次数
if (arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
exchange = true;
}
if (!exchange)
return;
}
}
int main()
{
int arr[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
int length = sizeof arr / sizeof(arr[0]);
cout << "排序前: ";
for (int i = 0; i < length; ++i)
cout << arr[i] << " ";
cout << endl;
BubbleSort(arr, length);
cout << "排序后: ";
for (int i = 0; i < length; ++i)
cout << arr[i] << " ";
cout << endl;
}
解法二:
#include <iostream>
#include <vector>
using namespace std;
void bubblesort(vector<int>& nums)
{
int n = nums.size();
int flag;
for (int j = n - 1; j > 0; --j)
{
flag = 0;
for (int i = 0; i < j; ++i)
{
if (nums[i] > nums[i + 1])
{
swap(nums[i], nums[i + 1]);
flag = 1;
}
}
if (flag == 0) break;
}
}
int main()
{
vector<int> vec;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int a;
cin >> a;
vec.push_back(a);
}
cout << "排序前:";
for (auto c : vec)
cout << c << " ";
cout << endl;
bubblesort(vec);
cout << "排序后:";
for (auto c : vec)
cout << c << " ";
return 0;
}