小学排序,当我尝试运行此代码时,我收到此错误 [英] Elementary Sorting, When I try running this code I get this error

查看:83
本文介绍了小学排序,当我尝试运行此代码时,我收到此错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码应该完成一些事情。它应该将现有数组INTO排序为一个新数组(已排序),从最小到最大。此外,它实现了这一点,而不使用java的内置排序(.sort,插入,冒泡等)。我遇到的问题是,当涉及从旧数组中交叉值时,它们不会再次出现在循环中。理想情况下,我应该能够运行它并从原始数组(未排序)和新数组(从最小到最大排序)中打印出来。



任意建议?





The following code is supposed to accomplish a few things. It is supposed to sort an existing array INTO a new array (sorted), from smallest to largest. In addition, it achieves this without the use of java's built in sorting (.sort, insertion, bubble etc). I am having issues though when it comes to "crossing out" values from the old array so that they do not present themselves again in the loop. Ideally, I should be able to run this and get a print out of the original array (unsorted) and the new array (sorted from smallest to largest).

Any suggestions?


public class Lab1
{
  public static void main(String argv[])
  {
     int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
     int sorted[] = new int[7];

     for(int i = 0; i < ar.length; i++)
     {
     int smallest = ar[0];
     int index = 0;

         for(int j = 0; j < ar.length; j++)
         {
             System.out.println("ar[" + j + "] = " + ar[j]);
             if (ar[j] < smallest)
             {
                 smallest = ar[j];
                 index = j;
             }
         }

         sorted[i] = smallest;
         ar[index] = Integer.MAX_VALUE;
      }

      for (int i = 0; i < sorted.length; i++)
      {
          System.out.println("sorted[" + i + "] = " + sorted[i]);
      }
   }
}

推荐答案

我怀疑代码中有错误,它不应该汇编。

I suspect an error in your code, it should not compile at all.
int ar[] = 7, 5, 2, 8, 4, 9, 6 };



又有另一个错误


and there is another error in

int sorted[] = new int[0];



你需要给出的大小



否则,你应该尝试替换


you need to give the size of sorted

otherwise, you should try to replace

smallest = Integer.MAX_VALUE;



with


with

ar[index] = Integer.MAX_VALUE;


这篇关于小学排序,当我尝试运行此代码时,我收到此错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆