简体   繁体   English

Java 排序一个数组,append 它在另一个数组中

[英]Java sorting of an array and append it in another array

I want to perform a linear search though a[] and append the result to b[].我想通过 a[] 和 append 对 b[] 执行线性搜索。 Here is my code:这是我的代码:

public class sorting {
    static int a[]={10,12,14,2,1,3};
    static int  b[]=new int[a.length];

public static void fn()
{
    for(int i=0;i<a.length;i++)
    {
        for(int j=1;j<a.length;j++)
        {
            if(a[i]>a[j]){
                 b[i]=a[j];
            }
        }
    }   
}

I am getting output as 333101. I expect {1,2,8,10,12,30}.我得到 output 作为 333101。我期望 {1,2,8,10,12,30}。

Even after finding 1 as minimum, loop continues and find 10>3 and replaces 1 with 3. How do I stop the loop when a minimum is found?即使在找到 1 作为最小值之后,循环继续并找到 10>3 并将 1 替换为 3。找到最小值时如何停止循环?

You never initialize b[0] if a[0] is the smallest value in a .如果a[0]a中的最小值,则永远不会初始化b[0]

If you want to have a sorted Output in b you should probably to a compare including b in the if statement.如果你想在b中有一个排序的输出,你应该在if语句中进行比较,包括b

What would be the intended behaviour if some numbers are negative or multipe times in a ?如果 a 中的某些数字为负数或倍数,预期的行为a什么?

One possible approach similar to your code would be一种类似于您的代码的可能方法是

public static void fn() {
    for (int i = 0; i < a.length; i++) {
        b[i] = Integer.MAX_VALUE; // initialize with large value
        for (int j = 0; j < a.length; j++) {
            // search for Minimum bigger than last value already in b
            if (b[i] > a[j] && (i == 0 || a[j] > b[i - 1])) {
                b[i] = a[j];
            }
        }
    }
}
Try this approach.

public class Main
{
  public static void main (String[]args)
  {
    int a[] = { 10, 12, 14, 2, 1, 3 }, c;
    int b[] = new int[a.length];
    b = a;
    for (int i = 0; i < b.length; i++)
    {
    for (int j = i + 1; j < b.length; j++)
      {
        if (b[i] > b[j])
          {
            c = b[i];
            b[i] = b[j];
            b[j] = c;
          }
      }
    }
    for (int j = 0; j < b.length; j++)
    {
        if (j == 0)
          {
            System.out.print ("{"+b[j]+",");
          }else if(j == b.length-1){
            System.out.print(b[j]+"}");
          }else{
            System.out.print(b[j]+",");
          }
    }
  }
}

output:{1,2,3,10,12,14}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM