2016-01-14 48 views
1

親愛的同胞Stackoverflowers,Java:插入排序算法交換

我的交換方法不工作的插入排序方法;它不會交換我的數組元素。

我的插入排序算法有什麼問題?

package AlgoExercises; 

import java.util.Arrays; 

public class InsertionSort { 

    static int[] numbersArray = { 5, 2, 4, 6, 1, 3 }; 

    static void swap(int a, int b) { 
    int temp = a; 
    a = b; 
    b = temp; 
    } 

    static void insertionSort(int[] numbersArray) { 
    for (int i = 1; i < numbersArray.length - 1; i++) { 
     int j = i; 
     while ((j > 0) && (numbersArray[j] < numbersArray[j - 1])) { 
     swap(numbersArray[j], numbersArray[j - 1]); 
     j = j - 1; 
     System.out.println(Arrays.toString(numbersArray)); 
     } 
    } 
    } 

    public static void main(String args[]) { 
    insertionSort(numbersArray); 
    } 
} 

解決方案:

固定其中int被列入其參數[]交換方法後,掉現在的作品!我也編輯了numbersArray.length-1到numbersArray.length。

謝謝你的幫助!

package AlgoExercises; 

import java.util.Arrays; 

public class InsertionSort { 

    static int[] numbersArray = { 5, 2, 4, 6, 1, 3 }; 

    static void swap(int i, int j) { 
    int temp = numbersArray[j]; 
    numbersArray[j] = numbersArray[i]; 
    numbersArray[i] = temp; 
    } 

    static void insertionSort(int[] numbersArray) { 
    for (int i = 1; i < numbersArray.length; i++) { 
     int j = i; 
     while ((j > 0) && (numbersArray[j] < numbersArray[j - 1])) { 
     swap(j, j - 1); 
     j = j - 1; 
     System.out.println(Arrays.toString(numbersArray)); 
     } 
    } 
    } 

    public static void main(String args[]) { 
    insertionSort(numbersArray); 
    } 
} 
+0

你必須在你的數組中設置交換。目前情況並非如此。 –

+1

你的代碼裏面寫了** **! – Idos

+0

可能的重複http://stackoverflow.com/questions/32431061/simple-swap-in-java –

回答

1

Java是按值傳遞的語言,所以調換int變量傳遞給swap方法沒有什麼區別。您應該傳遞數組本身+兩個索引以交換方法,並在交換方法中修改數組。

static void swap(int[] arr, int i, int j) { 
    int temp = arr[j]; 
    arr[j] = arr[i]; 
    arr[i] = temp; 
} 

,並調用它

swap(numbersArray, j, j-1); 

請注意,我沒有檢查你插入排序實現的邏輯。這個答案只涉及交換問題。

+0

嗯,不,它不是價值,而是通過參考副本。 –

1

只給你思考的另一種方式,爲什麼你的現有swap方法不起作用:如果你寫這樣的代碼:

void swap(int a, int b) { 
    int t = a; 
    a = b; 
    b = t; 
} 

void callSwap() { 
    int x = 1; 
    int y = 2; 

    swap(x, y); 

    System.out.println(x + ", " + y); 
} 

可以「內聯」的swap方法,基本上將其複製到callSwap方法。在語義上等價代碼如下:

void callSwap() { 
    int x = 1; 
    int y = 2; 

    // Start of inlined swap method. 
    { 
    int a = x; 
    int b = y; 

    int t = a; 
    a = b; 
    b = t; 
    } 
    // End of inlined swap method. 

    System.out.println(x + ", " + y); 
} 

希望你不會指望xy有交換價值。

請注意,此行爲與變量名稱ab不同於xy的事實無關;我只是選擇他們是不同的。如果swap的參數爲xy,則在內聯時需要將它們重命名爲其他內容,因爲它們與xycallSwap完全分開。