package cn.zh.array;
import java.util.Arrays;
import java.util.Scanner;
/*
* 有一组学员的成绩{99,85,82,63,60},
* 将它们按升序排列。要增加一个学员的成绩,将它插入成绩序列,并保持升序
*/
public class ArraysCopy3 {
public static void main(String[] args) {
int[] score = { 99, 85, 82, 63, 60 };
Scanner sc = new Scanner(System.in);
System.out.println("请输入新增成绩:");
int addScore = sc.nextInt();
addArrays(score, addScore);
sc.close();
}
public static int[] arraysSort(int[] nums) {
boolean flag = true;
for (int x = 0; x < nums.length - 1; x++) {
for (int y = 0; y < nums.length - 1 - x; y++) {
if (nums[y] > nums[y + 1]) {
int temp = nums[y + 1];
nums[y + 1] = nums[y];
nums[y] = temp;
flag = false;
}
if(flag) {
break;
}
}
}
return nums;
}
public static int[] addArrays(int[] nums, int addScore) {
int[] newScore = new int[nums.length + 1];
for (int x = 0; x < newScore.length - 1; x++) {
newScore[x] = nums[x];
}
newScore[newScore.length - 1] = addScore;
arraysSort(newScore);
searchIndex(newScore, addScore);
System.out.println("插入成绩:\t" + Arrays.toString(newScore));
return newScore;
}
public static void searchIndex(int[] nums, int addScore) {
for (int x = 0; x < nums.length; x++) {
if (nums[x] == addScore) {
System.out.println(addScore + "的下标是:" + x);
break;
}
}
}
}
int[] newScore = new int[nums.length + 1];
插入数组就是创建一个新数组来接收原数组的元素,
新数组的长度为原数组.length+1,
for (int x = 0; x < newScore.length - 1; x++) {
if (x < index) {
newScore[x] = nums[x];
} else {
newScore[x + 1] = nums[x];
}
newScore[index] = Score;
}
通过这种方式把数组元素后移(本质上就是覆盖后一位)
然后在特定位置插入新元素
for (int x = 0; x < newScore.length - 1; x++) {
newScore[x] = nums[x];
}
newScore[newScore.length - 1] = addScore;
Arrays.sort(newScore);
或者把插入的新元素直接给最后一位(新数组最后一位为0),然后排序一下
总结:两种方法类似,第一种方法因为后移覆盖,把新元素赋值给空出来的位置(适合在特定位置插入元素),
第二种没有后移覆盖,直接赋给新数组的最后一位。
还有一个简化版的,用的是java写好的工具类
https://blog.csdn.net/weixin_43715906/article/details/90674686