Maintain ascending order, insert elements into the array

Enter a number, keep it in ascending order, and insert it into the array

Problem-solving ideas:

  • The user enters a value x from the console
  • Find the subscript n where the inserted value should be inserted
  • Starting from the element of the subscript, cover the following elements in turn
  • Replace arr[n] with x value
  • Finally traverse the array

running result:
Insert picture description here

Code:

private static void demo() {
    
    
        int [] arr={
    
    10,20,30,40,50,60,70,0};    //定义数组,最后一个不赋值
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你要插入的元素:");
        int x = sc.nextInt();   //用户输入要插入的值
        //1,找到应该插入的下标 n
        int n=arr.length-1; //默认值为最后一个,找第一个比x大的下标
        for (int i = 0; i < arr.length; i++) {
    
    
            if (arr[i]>x){
    
    
                n=i;    //将找的下标赋值给 n
                break;
            }
        }

        //2,从n开始,依次向后移位
        for (int i = arr.length-2; i >=n ; i--) {
    
    
            arr[i+1]=arr[i];
        }

        //用x替换arr[n]
        arr[n]=x;

        //遍历数组
        for (int i = 0; i < arr.length; i++) {
    
    
            System.out.print(arr[i]+"\t");
        }

    }

Guess you like

Origin blog.csdn.net/weixin_44889894/article/details/110633171
Recommended