2012-02-09 43 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