簡體   English   中英

我在向已經按字母順序排列的數組中添加項目時遇到問題

[英]I'm having trouble adding an item to an already alphabetized array

到目前為止,我有下面的內容,但我如何確保要添加的項目返回到它的字母順序點? 我在初學者班級,所以我不能使用ArrayLists或與它們相關的方法。

任何形式的幫助或推動正確的方向將不勝感激。 謝謝!

該方法應遵循以下說明:

     - Adds an item to the list.  This method assumes that the list is already
      sorted in alphabetical order based on the names of the items in the list.

     - The new item will be inserted into the list in the appropriate place so
      that the list will remain alphabetized by names.

      In order to accommodate the new item, the internal array must be re-sized 
      so that it is one unit larger than it was before the call to this method.


public void add(Listable itemToAdd) {
         Listable[] items1;
         int newlength = items.length+1;
         items1 = new Listable [newlength];
         for(int i = 0;i<items.length;i++){
             items1[i] = items[i];
             items1[newlength-1] = itemToAdd;
         }
    }   

一開始就不錯! 我們需要做很多事情。 這條線

items1[newlength-1] = itemToAdd;

需要從循環中出來,並在之后放置 - 你只需將一些數組元素設置為此值,是,不是很多次?

復制部分是一個良好的開端。 你需要做的是

  1. 找到新元素應該去的位置(搜索數組,找到新元素應該去的元素)
  2. 復制新元素之前的元素
  3. 復制新元素
  4. 復制新元素之后的元素(調整它們的索引,因為它們都比以前更晚了!)

說得通?

如果您是初級班,您可能已經了解了插入排序 插入排序的一個有趣特性是,盡管在平均情況下運行時間很差( O(n 2 ),但在最佳情況下(排序列表)的性能非常好 - 實際上是O(n) 幾乎排序的列表將在相同的效率類中運行。 這可能是一種完成你想要做的事情的方法。 (它也可能是您使用插入排序的少數幾個地方之一,因此請充分利用它。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM