gpt4 book ai didi

java - 在 Java 中将数组排序为第二个数组

转载 作者:太空宇宙 更新时间:2023-11-04 12:34:16 26 4
gpt4 key购买 nike

我需要创建 2 个数组,并将一个数组按升序排列到另一个数组中并显示它。我已成功将 ar[] 移至排序[],但无法对其进行实际排序。
这是我到目前为止所拥有的:

public class SortArray
{
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-1; i++)
{
int smallest = 1000000;
int index = 0;

for (int j=i+1; j<sorted.length; j++)
{
if (ar[i] < smallest)
{
smallest=i;

int tmp = ar[i];
ar[i] = sorted[j];
sorted[j] = tmp;
}
}
}

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

最佳答案

在这里尝试理解和使用java算法。如果您在理解这个想法时遇到问题,请随时询问。 http://www.java2novice.com/java-sorting-algorithms/

它们效率更高并且不易出错。

假设您正在尝试学习排序算法和编码,这就是您正在尝试的内容;请注意,如果存在相同的值,则只会获取其中之一。

    int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[6];

int smallestFound=-1;
for (int i=0; i<ar.length-1; i++)
{
int smallest = 1000000;
for (int j=0; j<sorted.length; j++)
{
if (ar[j] < smallest && ar[j]>smallestFound) {
smallest = ar[j];
}
}
smallestFound=smallest;
sorted[i] = smallest;
}

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

关于java - 在 Java 中将数组排序为第二个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37504608/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com