0

This is my first insertion array, but it does not sort probably and I'm not sure where I went wrong. Any ideas?

  for (int i=1; i<array.length; i++) {
            int temp = array[i];
            for (int j=i-1; j >=0 && temp < array[j]; j--) {
                array[j+1] = array[j];
                array[j+1] = temp;
            }
            ItsATextArea.append(array[i] + "\n");
        }
4

3 回答 3

1

I think you are making mistake here

array[j+1] = array[j];
array[j+1] = temp;  // It must be array[j] = temp
于 2013-05-16T14:40:23.827 回答
1

你几乎是对的。'数组[j + 1] = temp;' 线应该在循环之外。

        for (int i=1; i<array.length; i++) {
            int temp = array[i];
            int j = i - 1;
            for (; j >=0 && temp < array[j]; j--) {
                array[j+1] = array[j];
            }                   
            array[j+1] = temp;
        } 

此外,如果您计划打印排序后的数组,请在算法完成后进行。因为你不能真正知道插入的元素“temp”是否在正确的位置,但在你添加“append”行的地方。例如,如果原始数组中的最后一个元素是最小的,则所有元素都需要向右移动一个位置。

于 2013-05-16T19:14:13.297 回答
0
array[j+1] = array[j];
array[j+1] = temp;

对我来说看起来有问题。您确定要在数组中使用相同的元素两次吗?

于 2013-05-16T14:37:53.587 回答