#include<iostream>
#include<string>
using namespace std;
void BubbleSort(int * list,int length) {
//设置一个变量,没有交换直接结束排序
int count=0;//用来计数
for (int i = 0; i < length - 1; i++) {
bool flog = true;
count++;
for (int j = 0; j < length - i - 1; j++) {
if (list[j] > list[j + 1]) {
flog = false;
int temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
if (flog == true) {
cout << "排序次数为" << count << endl;
return;
}
}
}
}
//打印数组
void PrintArr(int* List, int len) {
for (int i = 0; i < len; i++) {
cout << List[i] << " ";
}
}
int main() {
int len;
int arr[] = {42,25,55,26,88,72,99,100,101,102};
//计算数组的长度
len = sizeof(arr) / sizeof(arr[0]);
cout << "len=" << len << endl;
cout << "排序前,数组的内容为\n" << endl;
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl;
BubbleSort(arr, len);
cout << "排序后,数组的内容为:\n" << endl;
PrintArr(arr, len);
//system("");
return 0;
}
结果: