Files
ClassFeedback/C++代码/未命名2.cpp

50 lines
844 B
C++

#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
int n;
int arr[100100];
// 专门用来打印当前这个数组的元素
void print(){
for(int i = 1; i <= n; i++){
cout << arr[i] << " ";
}
cout << endl;
}
int main(){
cin >> n;
for(int i = 1; i <= n; i++){
cin >> arr[i];
}
// 冒泡排序:通过相邻元素的比较和交换,使得每一趟循环都能将当前未排序部分的最大值“冒泡”到末尾
for(int i = 1; i <= n - 1; i++) { // i是指趟数
// 第i趟
bool ok = true; // 我认为没有进行交换
for(int j = 1; j <= n - i; j++){ // j是指第一个元素 j+1表示第二元素
if(arr[j] > arr[j+1]){
swap(arr[j], arr[j+1]);
ok = false;
}
}
if(ok){
break;
}
cout << "第" << i << "趟:";
print();
}
// 原数组 5 3 8 1 4
// 第一趟 3 5 1 4 8
// 第二趟 3 1 4 5 8
// 第三趟 1 3 4 5 8
// 第四趟 1 3 4 5 8
return 0;
}