Simplification of insert sort exercises in java arrays

Title: There is a set of unsorted letters {e, v, c, a, u,'} in ascending order.
To add a new letter, insert it into the alphabetical sequence and keep it in ascending order.

Note: The title was meant to be an array {e,v,c,a,u} where there was already a place for new letters to be added

When you initially choose to enter a letter from the keyboard, you use the charAt() function to convert when you enter a letter on the keyboard because the String type cannot be converted to a char type one level lower than it:

System.out.println("Please enter a new letter");
        char nNum = input.next().charAt(0);

After defining a random array, sort it as required:

char[] num ={'e','v','c','a','u',' '};
        Arrays.sort(num);

A series of piecewise analyses were performed on the slag as new letters were entered for insertion.

They are divided into three sections: 1 when the letter entered is the minimum value, 2 when the letter entered is the middle value, and 3 when the letter entered is the maximum value:

(The code was messy, messy, and complex by me)

System.out.println("Please enter a new letter");
        char nNum = input.next().charAt(0);
      //  System.out.print(nNum);//Value of output letter
        if(nNum<num[1]){
           // System.out.println("test0");
            num[0]=nNum;
            for (int i = 0; i <num.length; i++) {
                System.out.println("After insertion:");
                System.out.print(num[i]+" ");
            }
        }else{
            for (int i = 2; i < num.length; i++) {
                if(nNum<num[i]){
                    for (int j = 0; j <i-1 ; j++) {
                        num[j]=num[j+1];
                    }
                    num[i-1]=nNum;
                  //  System.out.println("test1");
                    break;
                }
                else if(nNum>num[num.length-1]){
                    for (int j = 0; j <num.length-1; j++) {
                        num[j]=num[j+1];
                    }
                    num[num.length-1]=nNum;
                 //   System.out.println("test2");
                    break;
                }
            }

This is really based on the consideration of problem solving before optimization, and the above results are obtained.

After several optimizations and asking Big Shen Brother, the optimized code is as follows:

        int temp=-1;//Define a temporary object to save subscript values at initialization
        System.out.println("Please enter a new letter");
        char nNum = input.next().charAt(0);
        //  System.out.print(nNum);//Value of output letter
        for (int i =0; i <num.length-1 ; i++) {
            if(nNum>num[i+1]){
                num[i]=num[i+1];
                temp = i;
            }
        }num[temp+1]=nNum;

Is it really too simple after optimization?So it's really amazing and awesome ~

Posted on Tue, 04 Feb 2020 13:25:11 -0500 by samsunnyuk