在Java中对数组进行排序,然后进行打印

时间:2015-09-29 19:01:07

标签: java arrays

我的代码中有一个错误,因为它在排序后没有打印数组的所有元素。有人可以发现它并帮助我吗? (我只在Java的第5周,所以肯定是新手!)

public class Test01 {
public static void main(String[] args) {
    int[] arr = {1, 3, 5, 4, 2};        
    for (int i = 0; i < arr.length - 1; i++) { 
        int currentMin = arr[i];
        int currentMinIndex = i;

            for (int j = i + 1; j < arr.length; j++) {
                if (currentMin > arr[j]){
                    currentMin = arr[j];
                    currentMinIndex = j;
                }
            }
            if (currentMinIndex != i) {
                arr[currentMinIndex] = arr[i];
                arr[i] = currentMin;    
            }
            System.out.print(arr[i] + " ");
    }
}
}

目前的输出是: 1 2 3 4

所以我只是缺少打印'5'

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

您正在运行循环索引简短。改变

for (int i = 0; i < arr.length - 1; i++) {  // The -1 is the issue

for (int i = 0; i < arr.length ; i++) { 

答案 1 :(得分:0)

public class Test01 {
   public static void main(String[] args) {
      int[] arr = {1, 3, 5, 4, 2};
         for (int i = 0; i < arr.length; i++) {
            int currentMin = arr[i];
            int currentMinIndex = i;

            for (int j = i + 1; j < arr.length; j++) {
                if (currentMin > arr[j]){
                    currentMin = arr[j];
                    currentMinIndex = j;
                }
            }
            if (currentMinIndex != i) {
                arr[currentMinIndex] = arr[i];
                arr[i] = currentMin;
            }
            System.out.print(arr[i] + " ");
        }    
    }
}