最常见的Java常见面试题问答(4)

发表于:2013-01-24来源:ImportNew作者:不详点击数: 标签:java
插入元素到一个有序数组 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 package bigo; import java.util.Arrays; public class InsertingEle

  插入元素到一个有序数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package bigo;
 
import java.util.Arrays;
 
public class InsertingElementsToArray {
 
    public static void insertSortedArray(String toInsert) {
 
        String[ ] sortedArray = { "A", "C", "D" };
 
        /*
         * Binary search returns the index of the search item
         * if found, otherwise returns the minus insertion point. This example
         * returns index = -2, which means the elemnt is not found and needs to
         * be inserted as a second element.
         */
        int index = Arrays.binarySearch(sortedArray, toInsert);
 
        if (index < 0) {                                   // not found.
 
            // array indices are zero based. -2 index means insertion point of
            // -(-2)-1 = 1,  so insertIndex = 1
            int insertIndex = -index - 1;
 
            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] = toInsert;
            System.out.println(Arrays.toString(newSortedArray));
        }
    }
 
    public static void main(String[ ] args) {
        insertSortedArray("B");
    }
}

原文转自:http://www.importnew.com/871.html