补全9月11日至13日课评:为13名学生创建请假文档,为5个班级创建总结文档
This commit is contained in:
36
C++代码/CSP04/02-简单排序/03计算排序后的交换次数.cpp
Normal file
36
C++代码/CSP04/02-简单排序/03计算排序后的交换次数.cpp
Normal file
@@ -0,0 +1,36 @@
|
||||
#include <bits/stdc++.h>
|
||||
#define endl '\n'
|
||||
using namespace std;
|
||||
|
||||
int n, cnt = 0;
|
||||
int arr[100100];
|
||||
|
||||
void insertion(int n){
|
||||
for(int i = 2; i <= n; i++){ // i前面的都是有序的
|
||||
int curr = arr[i]; // 当前乱序的第一个
|
||||
int j = i - 1;
|
||||
while(j >= 1 && arr[j] > curr){
|
||||
cnt++;
|
||||
arr[j+1] = arr[j];
|
||||
j--;
|
||||
}
|
||||
j++;
|
||||
|
||||
arr[j] = curr;
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
cin >> n;
|
||||
for(int i = 1; i <= n; i++) {
|
||||
cin >> arr[i];
|
||||
}
|
||||
|
||||
insertion(n);
|
||||
|
||||
for(int i = 1; i <= n; i++) {
|
||||
cout << arr[i] << " ";
|
||||
}
|
||||
cout << endl << cnt;
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user