Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Sorting an Array and Inserting an Element in Java



Arranging the elements of an array in a specific sequence is known as sorting. Typically, sorting places the elements in either ascending or descending order.

Sorting Array and Inserting an Element

The Arrays.sort() method arranges the elements of an array in ascending order. After sorting, insertElement() can be used to insert a new element in the correct position to keep the array sorted.

Syntax

Following is the syntax for java.util.Arrays.sort() method:

public static void sort(Object[] a, int fromIndex, int toIndex)

Java Program to Sort an Array and Insert an Element

The following example shows how to use the sort () method and the 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;
   }
}

Output

Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Didn't find 1 @ -6
With 1 added: [length: 11]
-9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8 

Code Explanation

The code sorts an array using Arrays.sort(). It then tries to find the position of element 1 using Arrays.binarySearch(). Since 1 is not in the array, a new index is calculated to insert it in the correct position while maintaining the sorted order. The insertElement() method adds the new element to the array, and the printArray() method displays the updated array.

java_arrays.htm
Advertisements