算法
遍历数组,在此查看N+1的元素是不是比N元素大,如果大则交换位置,每次遍历后保证本次遍历最大的元素在最后
#include <iostream>
using namespace std;
void bubble_sort(int* arr, int length) {
bool tidy; // 判断数组是否已经有序
for (int i = 0; i < length; i ++) {
tidy = true;
for (int j = 0; j < length; j ++) {
if (arr[j] > arr[j + 1]) {
tidy = false;
swap(arr[j], arr[j + 1]);
}
}
if (tidy) { // 如果有序则退出遍历
break;
}
}
}
int main() {
int* arr = new int[10];
for (int i = 0; i < 10; i ++) {
arr[i] = 10 - i;
}
for (int i = 0; i < 10; i ++) {
cout << arr[i] << " ";
}
cout << "\n";
bubble_sort(arr, 10);
for (int i = 0; i < 10; i ++) {
cout << arr[i] << " ";
}
return 0;
}