Insert an element in Array, Search and Sort Array by using java program

By: Saravanan Viewed: 153583 times  Printer Friendly Format    


In this tutorial we are going to see how to insert an element for specified index and how to search an element in array and not in array. 

import java.util.*;
public class ArrayExample
{
public static void main(String args[]) throws Exception
{
int a[] = {9, 4, 6, -3, -7, 2, 3, -2, 5, -9, 4};
Arrays.sort(a);
printArray("Sorted array", a);

int i = Arrays.binarySearch(a, 9);
System.out.println("Array have 9. " + i);

i = Arrays.binarySearch(a, 8);
System.out.println("Array have not 8." + i);

int i1 = -i - 1;
a = insertElement(a, 8, i1);
printArray("In array 8 is added", a);

}
private static void printArray(String message, int a[]) 
{
System.out.println(message + ": [length: " + a.length + "]");
for (int i=0, n=a.length; i<n; i++)
{
if (i != 0) System.out.print(", ");
System.out.print(a[i]);
}
System.out.println();
}
private static int[] insertElement(int original[], int element, int in)
{
int length = original.length;
int destination[] = new int[length+1];
System.arraycopy(original, 0, destination, 0, in);
destination[index] = element;
System.arraycopy(original, in, destination, in+1, length-in);
return destination;
}
}


Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial