冒泡排序
1.概念和图解
1.1 概念
冒泡排序是一种简单的交换排序方式。它的基本思想是:对所有相邻记录的关键字进行比较,若不满足排序要求,则将其交换,直到排序完成为止。
1.2 图解
例子:用排序冒泡排序(升序)4, 2, 5, 88, 4,
每一趟排序都能排好一个数
2. 代码实现
/**
* @Author: lwj
* @Date: 2022-06-04 20:27:33
* @Description:冒泡排序
* @FilePath: /Linux_C_C-plus-plus/数据结构与算法(C++)/算法/排序算法/Bubble_sort.cpp
**/
#include <iostream>
template <typename Type>
void print(const Type &arr, int size) //打印数组
{
for (int i = 0; i < size; i++)
{
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
template <typename Type>
void bubbleSort(Type *arr, int size) //冒泡排序
{
// Type tmp;
for (int i = 0; i < size - 1; i++)
{
for (int j = 0; j < size - i - 1; j++)
{
if (arr[j] < arr[j + 1])
{
// tmp = arr[j];
// arr[j] = arr[j + 1];
// arr[j + 1] = tmp;
std::swap(arr[j], arr[j + 1]); //调用STL交换函数,升序话把两个数交换
}
}
}
}
int main()
{
int arr[] = {4, 2, 5, 88, 4};
int count = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, count);
print(arr, count);
return 0;
}
3. 总结
冒泡排序是一种稳定的排序方式,比较和交换次数与初始顺序有关。最好的时间复杂度为O(n),最坏的为O(n^2);空间复杂度为O(1)。