我需要使此插入排序函數實質上將元素向右複製,直到需要移動的值位於正確的位置,但是,使用我正在使用的代碼通常最終會出現垃圾,並嘗試多次迭代獲得相同的結果。我無法理解爲什麼這不應該起作用。Java插入排序 - 向下複製值
public static void Sort(Comparable[] a) {
int n = a.length;
Comparable temp = 0;
int x;
// Starting with the element at index 1...
for (int i = 1; i < n; i++) {
// ...move to the left until we find one less
// than the current element.
for (int j = i; j > 0; j--) {
if (less(a[j], a[j - 1]))
{
temp = a[j];
for(x = j; x > 0 && less(temp, a[x]); x--)
{
a[x] = a[x - 1];
}
a[x] = temp;
//exch(a, j, j - 1);
}
else
break;
}
}
}
減(a,b)順便檢查一下< b。
哎,內環應該去,直到爲零,不需要檢查我,它會像'爲(INT J = I-1,J>時= 0; J- - )' –
我認爲你的inner for循環('for x = j; ...')實際上是用起始值覆蓋整個數組。從那裏開始。爲什麼你的邏輯如此複雜,向前迭代,然後向後,然後再與其他一些奇怪的調用一起後退?嘗試簡化,查找插入排序的算法。這不是複雜的。 –