0% found this document useful (0 votes)
37 views1 page

Java Examples - Array Sort and Insert

The document provides a Java code sample to sort an integer array and insert an element into the sorted array at a specific index. It uses the Arrays.sort() method to sort the array, Arrays.binarySearch() to find the insertion index, and a custom insertElement() method to copy elements and insert the new element into the destination array.

Uploaded by

charchit123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views1 page

Java Examples - Array Sort and Insert

The document provides a Java code sample to sort an integer array and insert an element into the sorted array at a specific index. It uses the Arrays.sort() method to sort the array, Arrays.binarySearch() to find the insertion index, and a custom insertElement() method to copy elements and insert the new element into the destination array.

Uploaded by

charchit123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

JAVA EXAMPLES - ARRAY SORT AND INSERT

http://www.tutorialspoint.com/javaexamples/arrays_insert.htm

Copyright tutorialspoint.com

Problem Description:
How to sort an array and insert an element inside it?

Solution:
Following example shows how to use sort method and user defined method insertElement to
accomplish the task.
import java.util.Arrays;
public class MainClass {
public static void main(String args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(array);
printArray("Sorted array", array);
int index = Arrays.binarySearch(array, 1);
System.out.println("Didn't find 1 @ "
+ index);
int newIndex = -index - 1;
array = insertElement(array, 1, newIndex);
printArray("With 1 added", array);
}
private static void printArray(String message, int array[]) {
System.out.println(message
+ ": [length: " + array.length + "]");
for (int i = 0; i < array.length; i++) {
if (i != 0){
System.out.print(", ");
}
System.out.print(array[i]);
}
System.out.println();
}
private static int[] insertElement(int original[],
int element, int index) {
int length = original.length;
int destination[] = new int[length + 1];
System.arraycopy(original, 0, destination, 0, index);
destination[index] = element;
System.arraycopy(original, index, destination, index
+ 1, length - index);
return destination;
}
}

Result:
The above code sample will produce the following result.
Sorted array: [length:
-9, -7, -3, -2, 0, 2,
Didn't find 1 @ -6
With 1 added: [length:
-9, -7, -3, -2, 0, 1,

10]
4, 5, 6, 8
11]
2, 4, 5, 6, 8

Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js

You might also like