我在使用递归快速排序算法时遇到了一些问题。元素未按正确顺序排序。输入数据也是具有重复条目的字符串。我使用整数来区分升序(1)和降序(-1)排序。枢轴是中间元素。每当比较重复条目时( compareTo(String s) 将返回 0),我比较当前索引并返回一个负数,如果正在比较的字符串的索引大于另一个的索引。我不确定到底出了什么问题。下面是代码
// Quick sort Algorithm
public void sort(int left, int right)
{
int i = left, j = right;
String mid;
mid = (String)vect.elementAt((left + right)/2);
while (i <= j)
{
// Compare the elements to the left
while ((i < right) &&
(compare((String)vect.elementAt(i), mid) < 0))
i++;
// Compare the elements to the right
while ((j > left) && (compare((String)vect.elementAt(j), mid) > 0))
j--;
if (i <= j)
{
if(i!=j)
swap(i, j);
i++;
j--;
}
}
// Recursively call the sort method until indices cross.
if(left < j)
sort(left, j);
if(i < right)
sort(i, right);
}
/*
* Compare method to compare the elements.
* type = 1, for ascending sort
* type = -1, for descending sort
*/
public int compare(String firstObj, String secondObj)
{
int resCompare = firstObj.compareTo(secondObj)*type;
if(resCompare == 0)
{
int index_firstObj = vect.indexOf(firstObj);
int index_secObj = vect.indexOf(secondObj);
if(index_firstObj < index_secObj)
return -1;
else
return 1;
}
return resCompare;
}
// Swap the elements at i and j.
public void swap(int i, int j)
{
String tmp1 = (String)vect.elementAt(i);
String tmp2 = (String)vect.elementAt(j);
vect.setElementAt(tmp1, j);
vect.setElementAt(tmp2, i);
}
示例:输入 = {"AA","BB","zz","cc","aa","AA","PP","hh" }; 升序排序输出 = {"AA","AA","BB","PP","aa","cc","hh","zz"}; 降序排序输出 = {"zz","hh","cc","BB","aa","PP","AA","AA"};
该算法中的问题可能不适用于升序排序以及其他一些输入数据。因此,在代码/逻辑中找到故障的任何帮助都将非常有帮助。在此先感谢。
已解决:无需查找 index_firstObj 和 index_SecondObj。如果 resCompare 为零,则不要做任何事情。public int compare(String firstObj, String secondObj) { int resCompare = firstObj.compareTo(secondObj)*type; 返回资源比较;}