这个排序数组的代码只能排序一个值,为什么?

时间:2014-07-01 19:13:18

标签: java arrays sorting

我编写了这个代码来对一维数组进行排序但是当我运行这个代码时,黑色表单只显示第二个数组中索引0中的最小数字... 这是我的代码:

import javax.swing.JOptionPane;

public class anything1 {

    public static void main(String[] args)
    {
        // inserting array
        int[] RandomArray = { 9, 5, 2, 3, 4, 22, 10, 8 };

        // sorting array
        int[] Sortedarray = new int[RandomArray.length];
        int count = 0;
        int x = 0;
        for (int i = 0; i < RandomArray.length; i++) {

            for (int j = 0; j < RandomArray.length; j++) {
                if (i != j & RandomArray[i] != 0) {
                    if (RandomArray[i] < RandomArray[j]) {
                        Sortedarray[count] = RandomArray[i];
                        x = i;
                    } else {
                        Sortedarray[count] = RandomArray[j];
                        i = j;
                        x = j;
                    }
                }
            }
            RandomArray[x] = 0;
            i = count;
            count = count + 1;
            System.out.println("Count is : " + count);

            // break;
        }

        // write random array

        for (int n = 0; n < RandomArray.length; n++) {
            System.out.println("This is new random array:" + RandomArray[n]);
        }

        // write sorted array

        for (int z = 0; z < Sortedarray.length; z++) {
            System.out.println("This is sorted array:" + Sortedarray[z]);
        }
    }
}

这是结果的照片结果,其他任何值其他索引0都是0我想知道如何将下一个最小数字放在索引1中然后下一个最小数字在索引2 ...

http://im55.gulfup.com/giGcht.png

1 个答案:

答案 0 :(得分:0)

我宁愿直接在数组中交换值而不是创建一个新数组。您的问题是,您在SortedArray中为每个j循环段定义了值。可以使用这样的东西:

    int [] randomArray = {9,5,2,3,4,22,10,8};
    int swap;

    for(int i=0; i<randomArray.length; i++){
        for(int j=0; j<randomArray.length; j++){
            if(i != j && randomArray[i] > randomArray[j]){
                swap = randomArray[i];
                randomArray[i] = randomArray[j];
                randomArray[j] = swap;
            }
        }
    }

如果您确实需要第二个阵列,可以复制原始阵列并使用副本。