簡體   English   中英

我的插入排序有什么問題?

[英]What's wrong with my insertion sort?

我正在嘗試使用基於插入的排序算法對大型數據文件進行排序,代碼運行良好,但輸出不正確。 我已經一遍又一遍地研究了它,但沒有結果,有人可以看到我哪里出問題了嗎?

public void sort(Comparable[] items) {
    for (int i = 1; i < items.length; i++) {
        Comparable temp = items[i];
        int j = i - 1;
        while (j >= 0 && items[j].compareTo(items[j]) > 0) {
            items[j + 1] = items[j];
            j = j - 1;
        }
        items[j] = temp;
    }
}

我產生的示例數據文件是...

2
1
3
5
9
6
7
4
8

顯然輸出應該是1,2,3,4 ...-但是我得到1 3 5 9 6 7 4 8 8

items[j].compareTo(items[j])應該是items[j].compareTo(temp) ,否則,您只是將項目與其自身進行比較-您需要將其與要插入的對象進行比較。

然后items[j] = temp; 也會導致ArrayIndexOutOfBoundsException因為在循環結束時, items[j]小於temp ,或者j == -1 ,因此我們需要在該位置之后插入-最簡單的解決方法是將其更改為items[j+1] = temp;

算法

for i ← 1 to length(A)
    j ← i
    while j > 0 and A[j-1] > A[j]
        swap A[j] and A[j-1]
        j ← j - 1

轉換為Java:

import java.util.*;

class InsertionSortTest {
    public static int[] insertionSort(int[] A) {
        for (int i = 1; i < A.length; i++) {
            int j = i;
            while (j > 0 && A[j-1] > A[j]) {
                int t = A[j];
                A[j] = A[j-1];
                A[j-1] = t;
                j--;
            }
        }
        return A;
    }

    public static void main (String[] args) {
        int[] arr = { 5, 3, 0, 2, 1, 4 };

        System.out.println(Arrays.toString(insertionSort(arr)));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM