[英]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.