图示
代码
import java.util.*;
import java.lang.*;
public class Main {
static Scanner scanner = new Scanner(System.in);
static int n, m;
static int[] a = new int[10010];
public static void main(String[] args) {
n = scanner.nextInt();
m = scanner.nextInt();
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
while (m-- > 0) {
int pos = n - 1; // 逆序找第一个不符合降序的位置
while (pos > 0 && a[pos - 1] > a[pos]) {
pos--;
}
pos--;
int pos2 = pos + 1; // 回头找最后一个大于a[pos]的位置
while (pos2 < n && a[pos2] > a[pos]) {
pos2 ++;
}
pos2--;
int temp = a[pos2]; // 交换两数
a[pos2] = a[pos];
a[pos] = temp;
for (int i = pos + 1, j = n - 1; i < j; i++, j--) { // 翻转下降序列
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
}