Insert an element in Array, Search and Sort Array by using java program
By: Saravanan
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;
}
}
Archived Comments
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Java program to get location meta data from an image
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program