javaarraysinsert

Inserting an element into an array in sorted order


I'm trying to add an element into an array in sorted order.

This is my code :

public class SortedInsertion {

    public static void main(String[] args) {

        int[] arr=new int[6];
        arr[0]=5;
        arr[1]=6;
        arr[2]=9;
        arr[3]=11;
        System.out.println(Arrays.toString(arr));
        insert(7,arr);


    }

    public static void insert(int val,int[] arr){
        int i;
        for(i=0;i<arr.length-1;i++){

            if(arr[i]>val)
                break;
        }
        for(int k=i;k<arr.length-1;k++){
            arr[k+1]=arr[k];
            arr[i]=val;
        }
        System.out.println(Arrays.toString(arr));


    }

}

I'm getting the output as: [5, 6, 9, 11, 0, 0]

[5, 6, 7, 9, 9, 9]

But the right out put is

5,6,9,11,0,0

5,6,7,9,11,0


Solution

  • Change the insert method like this:

        public static void insert(int val,int[] arr){
          int i;
          for(i=0;i<arr.length-1;i++){
            if(arr[i]>val)
              break;
          }
          for(int k=arr.length-2; k>=i; k--){
            arr[k+1]=arr[k];            
          }
          arr[i]=val;
          System.out.println(Arrays.toString(arr));
    
        }