冒泡排序
冒泡排序
1. 解决的问题
给序列排序
2. 核心知识
- 交换元素位置(升序)
- 若当前位置值比之后一个位置值大(squeue[i] > sequeue[i+1])
- 2层循环
- 第1层:需要执行交换的元素序列(需要执行交互的序列长度等于需要执行交换的次数)
- 第 2层:交换
- 每次第1层循环结束,最大的一个元素放置到当前需要交换的序列最后面
3. C++实现
#include <iostream>
using namespace std;
template<class T>
void bubble_sort(T (& nums)[8], int c) {
// 需要执行交换的未排好序的序列,每次都会减1
for (int i = c-1; i > 0; i--) {
// 冒泡,每次将最大值移到当前序列的最后的位置
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j+1]) {
// 交换前后位置的值
T temp = nums[j+1];
nums[j+1] = nums[j];
nums[j] = temp;
}
}
}
}
int main() {
int nums[] = {2, 4, 6, 7, 19, 30, 40, 60};
bubble_sort(nums, (int)(sizeof nums / sizeof nums[0]));
for (int num: nums) {
cout << num << " ";
}
cout << endl;
return 0;
}