Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 654
Arun Prakash Avatar asked Oct 18 '25 17:10

Arun Prakash


2 Answers

You can use the Arrays or Collections binarySearch function to get the position to insert the new value at, you will need to shift all elements from this position (if any) to the right

int position = Math.abs(Collections.binarySearch(sortedList, key)) - 1;

like image 184
yamit3 Avatar answered Oct 20 '25 08:10

yamit3


public class InsertInSortedArray {
        public static void main(String[] args) {
            int arr[] = {5, 6, 9, 11};
            Arrays.sort(arr);
            int k = 7;
            int index = findIndexToBeInserted(arr, k, 0, arr.length - 1);
            ArrayList<Integer> al = new ArrayList<>();
            for (int i : arr)
                al.add(i);

            al.add(index, k);
            for (int i : al)
                System.out.println(i);
        }

    private static int findIndexToBeInserted(int[] arr, int k, int start, int end) {
            if (k == 0)
                return 0;

            int mid = (start + end) / 2;

            if (k > arr[mid] && k < arr[mid + 1])
                return mid + 1;

            if (arr[mid] < k)
                return findIndexToBeInserted(arr, k, mid + 1, end);

            return findIndexToBeInserted(arr, k, start, mid - 1);
        }
    }
like image 34
Jay Shah Avatar answered Oct 20 '25 08:10

Jay Shah