C++: 冒泡排序Bubble Sort
C++: 冒泡排序
通过指针,数组,函数利用冒泡排序,实现整型数组的升序排列。
原理:
#include <iostream>
using namespace std;
void bublesort(int* arr, int len) {
int i, j, tmp;
for (i = 0; i < len; i++) {
for (j = 0; j < len - 1; j++) {
if (arr[j] > arr[j + 1]) {//相邻比较,如果满足条件则交换
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
}
int main()
{
int arr[] = { 9,1,5,8,3,7,4,6,2 };
cout << "排序前顺序:" << endl;
for (int i = 0; i < 9; i++)cout << arr[i];
bublesort(arr, 9);
cout << "\n排序后顺序:" << endl;
for (int i = 0; i < 9; i++)cout << arr[i];
system("pause");
return 0;
}
#include <iostream>
using namespace std;
template<typename T> //整数或浮点数皆可使用,若要使用类(class)或结构体(struct)时必须重载大于(>)运算符
void bubble_sort(T arr[], int len) {
int i, j;
for (i = 0; i < len - 1; i++)
for (j = 0; j < len - 1 - i; j++)
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}
int main() {
int arr[] = { 61, 17, 29, 22, 34, 60, 72, 21, 50, 1, 62 };
int len = (int)sizeof(arr) / sizeof(*arr);
bubble_sort(arr, len);
for (int i = 0; i < len; i++)
cout << arr[i] << ' ';
cout << endl;
float arrf[] = { 17.5, 19.1, 0.6, 1.9, 10.5, 12.4, 3.8, 19.7, 1.5, 25.4, 28.6, 4.4, 23.8, 5.4 };
len = (float)sizeof(arrf) / sizeof(*arrf);
bubble_sort(arrf, len);
for (int i = 0; i < len; i++)
cout << arrf[i] << ' ' << endl;
system("pause");
return 0;
}
posted on 2022-04-16 09:48 Michael_chemic 阅读(72) 评论(0) 编辑 收藏 举报