2013-08-29 147 views
2

我需要幫助使用選擇排序對整數數組進行排序。它不會爲一些重複排序。以下是我的演示/主要。使用數組進行選擇排序

02 
    20 
    01 

應該

01 
    02 
    20 

我演示/主:

public static void main(String[] args) { 


    SelectionSortArray[] ints = new SelectionSortArray[3]; 

    ints [0] = new SelectionSortArray(02); 
    ints [1] = new SelectionSortArray(20); 
    ints [2] = new SelectionSortArray(01); 

    System.out.println("Unsorted array: "); 

    for (int index = 0; index < ints.length; index++) { 
     System.out.println(ints[index]); 
    } 


    SelectionSort.selectionSort(ints); 

    System.out.println(" "); 

    System.out.println("Sorted array using selection sort: "); 

    for (int index = 0; index < ints.length; index++) { 
     System.out.println(ints[index]); 
    } 


} 
+0

爲什麼不使用'Collections.sort()'方法? – sanbhat

+0

@Sanbhat它可能是家庭作業,所以collections.sort可能不會出現問題 – Kevin

+0

@sanbhat我需要使用SelectionSort類/方法對整數數組進行排序。 – user2256002

回答

2

你在SelectionSortArraycompareTo方法不正確。如果當前對象小於另一個對象,則compareTo方法必須返回小於零的int,但您將其返回1

從鏈接Javadoc中引用:

比較此對象與指定對象爲順序。返回 負整數,零或正整數,因爲此對象比指定對象小 ,等於或大於此指定對象。

嘗試這些變化:

if (num == other.num) { 
    result = 0; // This was correct; no change here. 
} else if (num < other.num) { 
    result = -1; // Changed from 1 to -1. 
} else { 
    result = 1; // 1 or 2 is fine, as long as it's positive 
} 
+0

我會試試這個。感謝你目前的幫助。 – user2256002

0

你的CompareTo函數是錯誤的。只需將其更改爲:

public int compareTo(SelectionSortArray other) { 
    return num.compareTo(other.num);  
} 

的關鍵是-1/0/1的返回碼,而不是「0,1,2」您使用。

通常,如果您在比較內置類型,那麼將其委託給內置的比較運算符會更容易。

注意:要使用「num.compareTo」,您需要使用「Integer」而不是「int」。如果你想堅持「int」,你需要rgettman發佈的解決方案。

0

注意,所改動compareTo以來,

return Integer.compare(this.num,other.num) 

這是實現返回要返回什麼,但在一個簡潔的方式

public static int compare(int x, int y) { 
    return (x < y) ? -1 : ((x == y) ? 0 : 1); 
} 
如果你想看到打印輸出中

你在問題中列出的方式使用

System.out.format("%02d%n",ints[index].num); 

or alte r toString()return String.format("%02d",num)

您可能還想看看java.util.Arrays源代碼,以便了解其他類似方法的實現方式。另外考慮改變你的班級名稱,以表明它保存着號碼CustomNumber並封裝你的班級,以避免直接訪問num

並在代碼

SelectionSortArray[] ints = new SelectionSortArray[8]; 
    ints[0] = new SelectionSortArray(01); 
    ints[1] = new SelectionSortArray(02); 
    ints[3] = new SelectionSortArray(03); 
    ints[4] = new SelectionSortArray(04); 
    ints[5] = new SelectionSortArray(05); 
    ints[6] = new SelectionSortArray(06); 
    ints[7] = new SelectionSortArray(07); 
    ints[8] = new SelectionSortArray(08);//??? 

另一個有趣的捕捉如果你先用0一些這將是一個八進制數和允許的數字是0 - 7,因此你會看到上面的編譯錯誤。此外

System.out.println(0123); 
    System.out.println(0234); 

不會打印


0234 

你(UN)預期!

83 
156 

在代碼中使用八進制數字時要小心謹慎。