我有一个对象数组。每个对象都按字符串排序,该字符串是对象的成员。以下是保存的字符串
"Mead Johnson"
"Heartlight Corp Inc"
"Learning Horizons"
"Block Drug Co"
"Block Drug Co"
"Warner Lambert Consumer Healthcare"
"Novartis Consumer Health Inc"
"Bionutrics Health Products Inc"
"Warner Lambert Consumer Healthcare"
"Barilla America"
"Bionutrics Health Products Inc"
这是我得到的输出顺序:
"Bionutrics Health Products Inc"
"Block Drug Co"
"Block Drug Co"
"Heartlight Corp Inc"
"Learning Horizons"
"Barilla America"
"Mead Johnson"
"Novartis Consumer Health Inc"
"Warner Labert Consumer Healthcare"
"Warner Lambert Consumer Healthcare"
"Biobutrics Health Products Inc"
如您所见,列表几乎已经排序。我使用的代码在
下面private void sort(Manufacturer[] manuArray, int left, int right)
{
int pivotValue;
if(left < right)
{
pivotValue = pivot(manuArray, left,right);
sort(manuArray, left, pivotValue-1);
sort(manuArray, pivotValue+1,right);
}
}
private int pivot(Manufacturer[] manuArray, int left, int right)
{
int p = left;
String pivotName = manuArray[left].getName();
for(int i = left + 1; i <= right; i++)
{
if(manuArray[i].getName().compareToIgnoreCase(pivotName) < 0)
{
p++;
swap(manuArray, i, p);
}
}
swap(manuArray, p, left);
return p;
}
private void swap(Manufacturer[] manuArray, int i, int p)
{
Manufacturer tempManu1 = manuArray[i];
Manufacturer tempManu2 = manuArray[p];
manuArray[i] = manuArray[p];
manuArray[p] = tempManu1;
}
我似乎无法找到算法为什么不对某些项目进行排序的原因。有什么想法吗?
编辑:我发现了问题我的循环是:
for(int i = left + 1; i < right; i++)
如果需要:
for(int i = left + 1; i <= right; i++)
答案 0 :(得分:0)
尝试不要在循环中对1求和:
for(int i = left; i < right; i++)
{
...
如果没有,请尝试将此代码改编为您的代码。我通过增加距离而不是按字母顺序排序:
public static void ordenarChollos(List<CholloObjeto> chollostemp, int izq, int der) {
CholloObjeto pivote=chollostemp.get(izq);
int i=izq;
int j=der;
CholloObjeto aux;
while(i<j){
while(chollostemp.get(i).getDistance() <= pivote.getDistance() && i<j) i++;
while(chollostemp.get(j).getDistance() > pivote.getDistance()) j--;
if (i<j) {
aux = chollostemp.get(i);
chollostemp.set(i,chollostemp.get(j));
chollostemp.set(j,aux);
}
}
chollostemp.set(izq,chollostemp.get(j));
chollostemp.set(j,pivote);
if(izq<j-1)
ordenarChollos(chollostemp,izq,j-1);
if(j+1 <der)
ordenarChollos(chollostemp,j+1,der);
}