很抱歉,如果它的一个基本问题......插入排序 - 降序
我只是想了解更多关于算法...
我写了一个简单的代码升序进行插入排序,但由于某种原因,我无法使其按降序执行排序。
我试图改变对比密钥(而(ⅰ> 0 & & A [1]>键)至(i> 0 & & A [1] <键))..它似乎部分地工作,但在第一元素没有得到排序,我得到了下面的结果..有人让我知道我错在哪里?
public class InsertionSort {
public static void main(String args[]) {
int[] a = { 1,10,11,5, 9, 3, 2, 4 };
// Loop through the entire array length. Consider you already have one
// element in array, start comparing with
// first element
for (int j = 1; j < a.length; j++) {
// Get the key (The value that needs to be compared with existing
// values.
int key = a[j];
// Get the array index for comparison, we need to compare with all
// other elements in the array with
// key
int i = j - 1;
// While i > 0 and when key is less than the value in the array
// shift the value and insert
// the value appropriately.
//System.out.println(j);
while (i > 0 && a[i] < key) {
a[i + 1] = a[i];
i = i - 1;
a[i + 1] = key;
}
}
for (int k = 0; k < a.length; k++) {
System.out.println(a[k]);
}
}
}
对不起..我的测试数据不好,我没有意识到,当升序排列时,我没有碰到数组中的第一个元素。 – Learner 2013-03-08 16:01:33
不管怎么样,好的尝试@学习者继续努力工作。 – 2013-03-08 16:09:08
如果我没有错,那么a [i + 1] = key行不应该出自while循环吗? – Azeem 2016-10-14 12:49:20