package com.company;
import java.util.Scanner;
public class demo04 {
public static void main(String[] args) {
/**
? ? ? ? * 插入新元素 依舊保持原數(shù)組有序
? ? ? ? */
? ? ? ? int [] scores=new int[]{99,88,77,66,55,44};
? ? ? ? //1 獲取要插入的值
? ? ? ? System.out.println("請輸入你要插入的值" );
? ? ? ? Scanner scanner=new Scanner(System.in);
? ? ? ? int num=scanner.nextInt();
? ? ? ? //2 找到要插入的值
? ? ? ? int index=0;
? ? ? ? for (int i =0; i
if(num>scores[i]){
index=i;//把位置記錄下來
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
}
//3? 把元素向后移index<->length-1
? ? ? ? for (int i = scores.length-1; i>index; i--) {
scores[i]=scores[i-1];
? ? ? ? }
//4 插入新值
? ? ? ? scores[index]=num;
? ? ? ? //5 打印插入后的結(jié)果
? ? ? ? //降序
? ? ? ? System.out.println("降序");
? ? ? ? for (int i =0; i < scores.length; i++){
System.out.print(scores[i]+"\t");
? ? ? ? }
System.out.println();
? ? ? ? System.out.println("升序");
? ? ? ? for (int i = scores.length-1; i >=0; i--) {
System.out.print(scores[i]+"\t");
? ? ? ? }
}
}