已知数组a[]={12 23 26 45 58 60}是有序的

已知数组a[]={12 23 26 45 58 60}是有序的,输入一个数x,将它插入数组中,保证数组仍然是有序的

你题目的解答代码如下:

import java.util.*;//导包
class HelloWorld {
    public static void main(String []args) {
        Scanner sc = new Scanner(System.in);
        int i,n = 6;
        int a[] = new int[]{12,23,26,45,58,60,0};//最后0用来点位
        int x = sc.nextInt();
        for (i = n-1; i>=0; i--){
            if (a[i] < x)
                break;
            a[i+1] = a[i];
        }
        a[i+1] = x;
        n++;
        for (i=0;i<n; i++){
            System.out.print(a[i] + " ");
        }
    }
}

img

如有帮助,望采纳!谢谢!

你找到符合的位置。
然后把元素全都往后移动一格。
再把数字放到它的位置上。
例如 输入的是22,
那么它应该在数组下标为1的地方。
你把当前数组下标1以后的全部往后挪一格。
然后把22放到数组下标为1的地方。

public class Test
{
    public static void main(String args[])
    {
        //原有序数组,这里约定数组是升序排列
        int[] intArray = new int[]{12,23,26,45 ,58,60};
        int toInsert = 8;//待插入数据
        int subscript = 0;//下标
        //确定下标位置
        if(toInsert < intArray[0])
        {
            subscript = 0;
        }
        else if(toInsert > intArray[intArray.length - 1])
        {
            subscript = intArray.length;
        }
        else
        {
            //循环,确定插入下标位置
            for(int i=0; i<intArray.length; i++)
            {
                if(toInsert == intArray[i])
                {
                    subscript = i;
                }
                if(toInsert > intArray[i] && toInsert < intArray[i+1])
                {
                    subscript = i +1;
                }
            }
        }

        //定义新数组,将toInsert数据插入数组中
        int[] newArray = new int[intArray.length + 1];
        for(int i=0; i<intArray.length+1; i++)
        {
            if(i < subscript)
            {
                newArray[i] = intArray[i];
            }
            if(i == subscript)
            {
                newArray[i] = toInsert;
            }
            if(i > subscript)
            {
                newArray[i] = intArray[i-1];
            }
        }

        //打印插入数据后的新数组
        for(int i : newArray)
        {
            System.out.println(i);
        }
        System.out.println("插入下标为:" + subscript);
    }
}