2015-02-24 65 views
0

我有一個對象數組。每個對象都由一個對象成員的字符串排序。這裏是指儲存在弦,我的排序算法對對象數組進行排序時可能會遇到什麼問題?

"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

這是一個功課問題嗎?爲什麼當它是Java原生的時候會重新實現quicksort? – Necreaux 2015-02-24 19:40:53

+0

是的,我們必須創建自己的。 – WorthAShot 2015-02-24 19:41:44

回答

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); 
} 
+0

抱歉,我沒有按照您在帖子的for循環部分中提供的內容進行操作。 – WorthAShot 2015-02-24 20:03:45

+0

我的意思是在你的pivot函數中,從「left」開始for循環,而不是從「left + 1」開始,作爲消解嘗試。 – masana 2015-02-24 20:12:26

+0

在我的函數中,我使用while循環。我的chollostemp對象與你的manuArray對象相同。您正在使用getName,而我正在使用getDistance。按字母順序/以米爲單位的距離。 如果我在使用>或<=的語句比較裏面的距離,應該使用比較字符串java函數。 – masana 2015-02-24 20:16:40