關於陣列插入一個整數,不影響之前的升序
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("輸入");
int a = sc.nextInt();
int array [] = new int [] {2,3,5,6,7};
//查詢要插入數的下標
int index = -1;
for(int i=0;i<array.length;i++) {
if(a<array[i]) {
index = i;
break;
}
}
array = Arrays.copyOf(array, array.length+1);//陣列擴容
//下標前不動,下標後移動
if(index == -1) {
array[array.length-1] = a;
}else {
for (int i = array.length-1; i >index; i--) {
array[i] =array[i-1];
}
}
array[index] = a;
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+" ");
}