题目:有一组学员的成绩,将它们按降序排列,要增加一个学员的成绩,将它插入成绩序列,并保持降序
思路: 1)先将原本数组按降序排列
2)新建一个比原来数组长度大1的数组
3)将原来数组里的元素按顺序存储带新的数组中
4)使用Scanner获取你要增加的学员成绩
5)通过循环比较,获取插入元素要插入的位置(下标)
6)从插入位置开始及之后的元素依往后移动一位(注意:移动的时候,从后向前移动)
7)移动元素之后,插入位置就空出来了,将插入元素存储到插入位置
过程: 接下来我们根据我们的解题思路来一步步写代码
//设置数组
int[] scores = { 99, 85, 63, 60, 82 };
1)先将原本数组按降序排列
for (int i = 0; i < scores.length; i++) {
for (int j = i + 1; j < scores.length; j++) {
if (scores[i] < scores[j]) {
int temp = scores[i];
scores[i] = scores[j];
scores[j] = temp;
break;
}
}
}
//输出降序完毕的数组
System.out.println("降序后的数组为:");
for (int i = 0; i < scores.length; i++) {
System.out.print(scores[i] + " ");
}
2)新建一个比原来数组长度大1的数组
int[] newScores = new int[scores.length + 1];
3)将原来数组里的元素按顺序存储带新的数组中
for (int i = 0; i < scores.length; i++) {
newScores[i] = scores[i];
}
System.out.println();
4)使用Scanner获取你要增加的学员成绩
Scanner sc = new Scanner(System.in);
System.out.println("请输入增加的学员成绩");
int insert = sc.nextInt();
5)通过循环比较,获取插入元素要插入的位置(下标)
int index = 0;
for (int i = 0; i < newScores.length; i++) {
if (insert > newScores[i]) {
index = i;
// 一旦获取插入元素比某一个元素大,就不再往后进行比较
break;
}
}
6)从插入位置开始及之后的元素依往后移动一位(注意:移动的时候,从后向前移动)
for (int i = newScores.length - 1; i > index; i--) {
newScores[i] = newScores[i - 1];
}
7)移动元素之后,插入位置就空出来了,将插入元素存储到插入位置
newScores[index] = insert;
// 插入元素之后,遍历新数组
System.out.println("插入成绩后的降序新数组为:");
for (int j = 0; j < newScores.length; j++) {
System.out.print(newScores[j] + " ");
}
完整结果如下:
为了方便大家使用,下面附上源码:
int[] scores = { 99, 85, 63, 60, 82 };
//1)先将原本数组按降序排列
for (int i = 0; i < scores.length; i++) {
for (int j = i + 1; j < scores.length; j++) {
if (scores[i] < scores[j]) {
int temp = scores[i];
scores[i] = scores[j];
scores[j] = temp;
break;
}
}
}
//输出降序完毕的数组
System.out.println("降序后的数组为:");
for (int i = 0; i < scores.length; i++) {
System.out.print(scores[i] + " ");
}
// 2)新建一个比原来数组长度大1的数组
int[] newScores = new int[scores.length + 1];
// 3)将原来数组里的元素按顺序存储带新的数组中
for (int i = 0; i < scores.length; i++) {
newScores[i] = scores[i];
}
System.out.println();
// 4)使用Scanner获取你要增加的学员成绩
Scanner sc = new Scanner(System.in);
System.out.println("请输入增加的学员成绩");
int insert = sc.nextInt();
// 5)通过循环比较,获取插入元素要插入的位置(下标)
int index = 0;
for (int i = 0; i < newScores.length; i++) {
if (insert > newScores[i]) {
index = i;
// 一旦获取插入元素比某一个元素大,就不再往后进行比较
break;
}
}
// 6)从插入位置开始及之后的元素依往后移动一位(注意:移动的时候,从后向前移动)
for (int i = newScores.length - 1; i > index; i--) {
newScores[i] = newScores[i - 1];
}
// 7)移动元素之后,插入位置就空出来了,将插入元素存储到插入位置
newScores[index] = insert;
// 插入元素之后,遍历新数组
System.out.println("插入成绩后的降序新数组为:");
for (int j = 0; j < newScores.length; j++) {
System.out.print(newScores[j] + " ");
}