Saturday, 25 September 2010

Inserting an Element into a Sorted Array

// Create anarray with an ordered list of items
String[] sortedArray = new String[]{"ant", "bat", "cat", "dog"};

// Search for a non-existent item and then insert it
int index = Arrays.binarySearch(sortedArray, "cow");
if (index < 0) { // Compute the insert index
    int insertIndex = -index-1; // Insert the new item into sortedArray. The example here creates
   // a new larger array to hold the new item.
   String[] newSortedArray = new String[sortedArray.length+1];
   System.arraycopy(sortedArray, 0, newSortedArray, 0, insertIndex);
    System.arraycopy(sortedArray, insertIndex, newSortedArray, insertIndex+1, sortedArray.length-insertIndex);
  newSortedArray[insertIndex] = "cow"
  sortedArray = newSortedArray;
}

No comments:

Post a Comment