2012-02-09 45 views
1

如果將整數按升序排序,您將如何插入排序數組。我被告知使用二分搜索,但那隻會返回元素的位置。以遞歸方式插入到排序列表中

僞代碼中的一個例子是grate。

+0

是它功課再加入功課標籤? – 2012-02-09 10:13:47

回答

2
  1. 使用二進制搜索(如果這是一個鏈表,可能是相當昂貴的迭代),以尋找到新的項目屬於
  2. 的位置,如果該值是相同的 - 什麼都不做
  3. 如果值是不同的,需要在這裏插入,這意味着將所有的事情從這個位置移回到一個結尾(如果這是一個鏈表,這意味着在這一點插入一個新節點,不必做所有的移動)
  4. 將新項目插入索引。
1

假設您使用的是靜態數組,例如沒有鏈表

以下是一種方式做字符串數組,你可以定製按您的要求

//與項目的有序列表 的String [] sortedArray =新的String [] {「螞蟻創建anarray 「,」蝙蝠「,」貓「,」狗「};

// 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; 
} 

參考http://www.exampledepot.com/egs/java.util/coll_InsertInArray.html