this solution maybe help you or notice for in a specific your problem
in a sorted array , a search operation is performed for the possible position of the givin element by using Binary search , and then an insert operation is performed followed by shifting the elements to the right way .
public class InsertElmSort {
// Inserting a key elements in arr[] of gevin.
//capacity . n is current size of arr[] .
//this function return n + 1 if insertion is successful,
//else return n .
static int insertSorted(int arr[] , int n , int key , int capacity ) {
int i;
for(i = n - 1 ; (i >= 0 && arr[i] > key); i-- ) {
arr[i + 1] = arr[i];
//the way 1
//arr[i] = key;
}
//the way 2 instead of above way 1 by out the for loops block
arr[i + 1] = key;
// can not access more elements if n is already
//more than or equal capacity
if(n >= capacity) {
return n;
}
return (n + 1);
}
public static void main (String args[]) {
int arr[] = new int[20];
arr[0] = 1 ;
arr[1] = 3 ;
arr[2] = 5;
arr[3] = 6;
arr[4] = 9;
arr[5] = 11;
int n = 6;
int capacity = arr.length;
int key = 7;
System.out.print("Before the insertion: ");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
//call function to inserting key .
n = insetSorted(arr , n , key , capacity);
System.out.print("\n After the insertion: ")
for(int i = 0; i < n ; i++) {
System.out.print(arr[i] + " ");
}
}
}
this solution maybe help you or notice for in a specific your problem
in a sorted array , a search operation is performed for the possible position of the givin element by using Binary search , and then an insert operation is performed followed by shifting the elements to the right way .
public class InsertElmSort {
// Inserting a key elements in arr[] of gevin.
//capacity . n is current size of arr[] .
//this function return n + 1 if insertion is successful,
//else return n .
static int insertSorted(int arr[] , int n , int key , int capacity ) {
int i;
for(i = n - 1 ; (i >= 0 && arr[i] > key); i-- ) {
arr[i + 1] = arr[i];
//the way 1
//arr[i] = key;
}
//the way 2 instead of above way 1 by out the for loops block
arr[i + 1] = key;
// can not access more elements if n is already
//more than or equal capacity
if(n >= capacity) {
return n;
}
return (n + 1);
}
public static void main (String args[]) {
int arr[] = new int[20];
arr[0] = 1 ;
arr[1] = 3 ;
arr[2] = 5;
arr[3] = 6;
arr[4] = 9;
arr[5] = 11;
int n = 6;
int capacity = arr.length;
int key = 7;
System.out.print("Before the insertion: ");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
//call function to inserting key .
n = insetSorted(arr , n , key , capacity);
System.out.print("\n After the insertion: ")
for(int i = 0; i < n ; i++) {
System.out.print(arr[i] + " ");
}
}
}