Inserting an Element into a Sorted Array
From Java Example Source Code
Contents |
[edit] Overview - Inserting an Element into a Sorted Array
This Java example program shows how to insert an element into a sorted array.
[edit] Java Source Code
- Package: example.array
- File: SearchTest.java
package example.array;
import java.util.Arrays;
public class SearchTest {
public static void main(String args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
// Ensure array sortedArrays.sort(array);
printArray("Sorted array", array);
// Search for element in arrayint index = Arrays.binarySearch(array, 2);
System.out.println("Found 2 at " + index);
// Search for element not in arrayindex = Arrays.binarySearch(array, 1);
System.out.println("Didn't find 1 at " + index);
// Insertint 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, n = array.length; i < n; 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;}}
[edit] What Result You Can Get
run the program, you will get:
Sorted array: [length: 10] -9, -7, -3, -2, 0, 2, 4, 5, 6, 8 Found 2 at 5 Didn't find 1 at -6 With 1 added: [length: 11] -9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8
[edit] Required External Libraries and/or Files for this Java Example
Need nothing.
[edit] How to Run this Java Example Program
We recommend running this Java example program with Eclipse.
For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.
It's fairly easy.
[edit] Question & Answer
Any question?
Click edit and post your question or answer here.
