gpt4 book ai didi

java - java中数组排序的算法

转载 作者:行者123 更新时间:2023-12-02 11:12:30 27 4
gpt4 key购买 nike

我想对一个int数组进行从小到大的排序。我已经创建了下一个算法,但问题是新数组没有从 if 语句接收到正确的值。我将把我的代码放在下面。

 public static void main(String[] args) {
int[] arr = {33,44,22,11,22,11};
int[] arrSort = new int[6];
int temp=0;
for (int i = 0; i < arrSort.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
temp = arr[i + 1];
arr[i + 1] = arr[i];
arrSort[i] = temp;
}

else {
arrSort[i] = arr[i];
}
}
System.out.println(Arrays.toString(arrSort));
}

如果我运行代码,我会得到下一个值:[33, 22, 11, 22, 11, 0];

我只是想弄清楚算法的哪一部分被认为是错误的。预先感谢您。

最佳答案

You need to apply 2 loops.
1st loop is to access 1st arr element.
2nd loop is to access next(1st + 1)th element.
After comparing 1st element with other swap it accordingly.

public static void main(String []args)
{
int[] arr = {33,44,22,11,22,11};
int len=arr.length;
int temp=0,i,j;

for (i = 0; i < len; i++)
{
for (j = i+1; j < len; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(i=0; i<arr.length; i++)
{
System.out.println(arr[i]);
}
}

关于java - java中数组排序的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50525399/

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