簡體   English   中英

字符串排序

[英]Sort Array of Strings

因此,我正在嘗試使用算法對字符串數組進行排序。

注意:對於此分配,我不允許使用任何內置的排序功能。

public boolean insert(String s)
{
  boolean result = false;
  int index = 0;
  int k = 0;
  String temp = "";

  if (numUsed < values.length)
  {
    if (index == 0) 
    {
      values[index] = s;
    }    
    else 
    {
      index = 0;
      while (values[index].compareTo(s) < 0);
      k = index;
      while (k < numUsed)
      {
        values[k + 1] = values[k];
      }
      values[index] = s;
    }
    numUsed++;
    result = true;
  }
}

給定“蘋果”,“貓”和“蜜蜂”的輸入,輸出的順序與輸入的順序相同。 不管我做什么,似乎都無法解決。

有人可以幫我找到問題嗎?

從基礎開始。 想象一下,有一大堆索引卡隨機排列在您面前,並且需要按字母順序對它們進行排序。 一種簡單但可行的方法是首先找到所有以A開頭的單詞,然后將它們放在單獨的堆中(提示:如何在程序中模擬單獨的堆?)。 然后,您經過第一堆,找到所有以B開頭的單詞,並將它們放在已排序的堆的后面 (另一個提示)。

我建議擱置您當前的代碼並重新開始。 編寫一個遍歷未排序數組的循環,並找到最接近字典開頭的單詞。 以下是一些偽代碼,可幫助您入門:

String leastSoFar = "ZZZZZZ";
for each String in values:
    compare the string to leastSoFar
    if the string is closer to the start of the dictionary than leastSoFar:
        leastSoFar = ???? //I'll let you fill those in

對集合進行排序和向集合中添加元素通常是兩個單獨的功能。 當然,可以按某種方式將元素添加到集合中,以便對元素進行排序……但這是與僅對元素數組進行排序完全不同的任務。

如果您只是嘗試實現一種簡單的排序算法,那么一個易於編寫的簡單(但不是最佳)算法就是“延遲替換排序”。 偽代碼fpr升序排序算法簡要描述如下:

 Begin DELAYEDSORT
     For ITEM=1 to maximum number of items in list-1
        LOWEST=ITEM
        For N=ITEM+1 to maximum number of items in list
           Is entry at position N lower than entry at position LOWEST?
              If so, LOWEST=N
        Next N
        Is ITEM different from LOWEST
           If so, swap entry at LOWEST with entry in ITEM
     Next ITEM
  End DELAYEDSORT

延遲替換排序算法易於理解且易於編碼。 它通常比氣泡排序更快(交換次數更少),但時間復雜度O(n ^ 2)仍然很差,因此不適用於對非常大的數據集進行排序。

如果您確實想將項目添加到已排序的集合中,則可以將新項目添加到集合的末尾,然后使用上面的方法重新使用它。 如果您使用的數據集大於幾百或幾千個元素,則效率會很差。

仍然具有O(n ^ 2)時間復雜度但可以將加法和排序結合起來的另一種解決方案是“插入排序”,其偽代碼如下所示:

// The values in A[i] are checked in-order, starting at the second one
for i ← 1 to i ← length(A)
  {
    // at the start of the iteration, A[0..i-1] are in sorted order
    // this iteration will insert A[i] into that sorted order
    // save A[i], the value that will be inserted into the array on this iteration
    valueToInsert ← A[i]
    // now mark position i as the hole; A[i]=A[holePos] is now empty
    holePos ← i
    // keep moving the hole down until the valueToInsert is larger than 
    // what's just below the hole or the hole has reached the beginning of the array
    while holePos > 0 and valueToInsert < A[holePos - 1]
      { //value to insert doesn't belong where the hole currently is, so shift 
        A[holePos] ← A[holePos - 1] //shift the larger value up
        holePos ← holePos - 1       //move the hole position down
      }
    // hole is in the right position, so put valueToInsert into the hole
    A[holePos] ← valueToInsert
    // A[0..i] are now in sorted order
  }

暫無
暫無

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

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