简体   繁体   English

字符串排序

[英]Sort Array of Strings

So I am trying to sort an array of strings with an algorithm. 因此,我正在尝试使用算法对字符串数组进行排序。

NOTE: For this assignment I am not allowed to use any of the built in sort functions. 注意:对于此分配,我不允许使用任何内置的排序功能。

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

Given the input of "apples", "cats", and "bees" the output is in the same order that it was input. 给定“苹果”,“猫”和“蜜蜂”的输入,输出的顺序与输入的顺序相同。 No matter what I do it just never seems to sort. 不管我做什么,似乎都无法解决。

Can someone help me find the problem? 有人可以帮我找到问题吗?

Start by going back to basics. 从基础开始。 Imagine you have a large pile of index cards randomly sorted in front of you, and you need to alphabetize them. 想象一下,有一大堆索引卡随机排列在您面前,并且需要按字母顺序对它们进行排序。 A simple but workable method is to first find all the words starting with A, and putting those in a separate pile (hint: how can you mimic a separate pile in your program?). 一种简单但可行的方法是首先找到所有以A开头的单词,然后将它们放在单独的堆中(提示:如何在程序中模拟单独的堆?)。 Then you go though the first pile, find all the words starting with B, and putting those in the back of your sorted pile (another hint). 然后,您经过第一堆,找到所有以B开头的单词,并将它们放在已排序的堆的后面 (另一个提示)。

I'd recommend putting your current code aside and starting fresh. 我建议搁置您当前的代码并重新开始。 Write a loop that goes through the unsorted array, and finds the word closest to the beginning of the dictionary. 编写一个遍历未排序数组的循环,并找到最接近字典开头的单词。 Here's some psuedocode to get you started with that: 以下是一些伪代码,可帮助您入门:

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

Sorting a collection and adding elements to a collection are, often, two separate functions. 对集合进行排序和向集合中添加元素通常是两个单独的功能。 It is, of course, possible to add elements to a collection in a manner such that the elements are sorted ... but this is a very different task from simply sorting an array of elements. 当然,可以按某种方式将元素添加到集合中,以便对元素进行排序……但这是与仅对元素数组进行排序完全不同的任务。

If you are simply trying to implement a simple sorting algorithm, a simple (but not optimal) algorithm that is easy to code is the "delayed replacement sort". 如果您只是尝试实现一种简单的排序算法,那么一个易于编写的简单(但不是最佳)算法就是“延迟替换排序”。 Pseudocode fpr the algorithm to sort into ascending order is described succinctly below: 伪代码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

The delayed replacement sorting algorithm is simple to understand and easy to code. 延迟替换排序算法易于理解且易于编码。 It is typically faster than the bubble sort (fewer swaps), but still has bad time complexity O(n^2) and so it is not appropriate for sorting very large datasets. 它通常比气泡排序更快(交换次数更少),但时间复杂度O(n ^ 2)仍然很差,因此不适用于对非常大的数据集进行排序。

If you really want to add items to a sorted collection, then you can add the new item to the end of your collection, and resort it using the above. 如果您确实想将项目添加到已排序的集合中,则可以将新项目添加到集合的末尾,然后使用上面的方法重新使用它。 If you are working with data sets larger than a few hundred or thousand elements, then efficiency will be poor. 如果您使用的数据集大于几百或几千个元素,则效率会很差。

An alternate solution that still has O(n^2) time complexity but which can be adapted to combine the adding and sorting is the "insertion sort" whose pseudocode appears below: 仍然具有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